Возвращение переменной из функции - PullRequest
1 голос
/ 22 апреля 2020

У меня есть страница главной функции, и я связал следующую страницу с кнопкой, когда я нажимаю кнопку, она выполняет функцию на главной странице, но. я хочу использовать результат из функции в другом файле в качестве переменной


########main.py

class Main(object):
    def __init__(self,master):
        self.master = master
        mainFrame = Frame(self.master)
        mainFrame.pack()


        topFrame= Frame(mainFrame,width=1050,height =50, bg="#f8f8f8",padx =20, relief =SUNKEN,
                        borderwidth=2)
        topFrame.pack(side=TOP,fill = X)

    self.btnselfolder= Button(topFrame, text="Select Folder", compound=LEFT,
                              font="arial 12 bold", command=self.selectFolder)
        self.btnselfolder.pack(side=LEFT)

    def selectFolder(self):
        print("folder")
        return folder

################# selectfolder page


class Page2(Toplevel):

    def __init__(self):
        Toplevel.__init__(self)
        self.geometry("450x300")
        self.title("page2")
        self.resizable(False,False)

        self.topFrame = Frame(self, width=350,height=150, bg="white")
        self.topFrame.pack(fill=X)

    # call the function from main.py and it will give me the same output folder

    y = selectFolder()


Ответы [ 2 ]

2 голосов
/ 22 апреля 2020

Так как метод selectFolder не является c, вам нужно получить к нему доступ, используя экземпляр. Например:

main = Main()
folder = main.selectFolder()

folder должно содержать возвращенное вами значение.

0 голосов
/ 22 апреля 2020

Боюсь, когда я просто скопировал и вставил ваш код непосредственно в мой IDLE, это сразу же дало мне ошибки в именовании. Даже окно Tkinter не появилось. Чтобы прояснить ситуацию, я бы go о создании окна Tkinter, как показано ниже. Также я не знаю, как на самом деле не использую или не знаю, как интегрировать классы с самим Tkinter, но я быстро научился, как на ваших ошибках:)

# import tkinter from the libraries
from tkinter import *
import os
# the Zen of Python

#import this


# declare the tkinter window variable
# scroll to bottom to see mainloop
root = Tk()

########main.py

# folder is not defined as a variable
# but i recommend looking into
# using system of which i imported
# for you. You can research how to
# use it yourself for good practice
# i am sorry if i am wrong about this
# but my impression is you're trying to
# use the OS to select a folder from a
# directory. So the 'selectFolder' function
# should not be declared as a method within the class
# therefore rendering the Page2 class useless.


def selectFolder():
    print("folder")

    # return will result in an error
    # because it has not been declared as a variable
    # return folder

class Main():
    # all instances instantiated (created)
    # within the __init__ method
    # must be declared in the parentheses
    def __init__(self, topFrame, btnselfolder):

        # instantiate the topFrame object
        self.topFrame = topFrame

        # instantiate the btnselfolder
        self.btnselfolder = btnselfolder


    # pro tip - when having multiple
    # arguments within an object, then
    # to keep it clean and easy to read
    # space out the code like i have for
    # you. You should also read the "Zen of Python"
    # which is at the top as 'import this'
    # however i have commented it out for you
    topFrame = Frame(root,
                     width=1050,
                     height = 50,
                     bg = "#f8f8f8",
                     padx = 20,
                     relief = SUNKEN,
                     borderwidth=2)

    topFrame.pack(side=TOP, fill = X)

    btnselfolder = Button(topFrame,
                          text = "Select Folder",
                          compound=LEFT,
                          font = "arial 12 bold",
                          command = selectFolder).pack()

# mainloop() method will keep the window open
# so that it doesn't appear for a millisecond
# and dissapear :)
root.mainloop()

# I hope this has been a big help
# Thanks for posting this question! :-)
# Enjoy your day, good luck and be safe in Lockdown!

Еще раз спасибо за вопрос, мне очень понравилось решать это или, по крайней мере, дает вам некоторое руководство! :)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...