简体   繁体   English

如何将值从一个 class 返回到另一个?

[英]How to return value from one class to another?

I am trying to return entry_username from class Window1 to class named Window2 .我正在尝试将entry_username从 class Window1返回到名为Window2的 class 。

My full code is found at the bottom我的完整代码在底部

My goal is to show a Label inside Window2 that shows the username that just logged in from Window1我的目标是在Window2中显示一个 Label 显示刚刚从Window1登录的用户名

I am using Notebook inside windows2 bearing in mind.记住,我在 windows2 中使用笔记本。

Here is what I have tried inside Window2 :这是我在Window2中尝试过的:

self.User = Label(main, text = Window1().entry_username.get())

But this returns me a error of:但这会给我一个错误:

TypeError: __init__() missing 1 required positional argument: 'master'

My password file:我的密码文件:

test:1

def main():
    root = Tk()
    app = Window1(root)

    root.mainloop()

class Window1:
    def __init__(self,master):
        self.master = master
        self.master.title("User Log In")
        self.master.geometry('400x150')
        self.frame = Frame(self.master)
        self.frame.pack(fill="both", expand=True)


        self.label_username = Label(self.frame, text="Username: ",font=("bold",16))
        self.entry_username = Entry(self.frame, font = ("bold", 14))
        self.label_password = Label(self.frame, text="Password: ",font=("bold",16))
        self.entry_password = Entry(self.frame, show="*", font = ("bold", 14))

        self.label_username.pack()
        self.entry_username.pack()
        self.label_password.pack()
        self.entry_password.pack()

        self.logbtn = Button(self.frame, text="Login", font = ("bold", 10), command=self._login_btn_clicked)
        self.logbtn.pack()



    def _login_btn_clicked(self):
        # print("Clicked")
        username = self.entry_username.get()
        password = self.entry_password.get()

        # print(username, password)
        account_list = [line.split(":", maxsplit=1) for line in open("passwords.txt")]
        # list of 2-tuples. Usersnames with colons inside not supported.
        accounts = {key: value.rstrip() for key, value in account_list}
        # Convert to dict[username] = password, and slices off the line ending.
        # Does not support passwords ending in whitespace.
        if accounts[username] == password:
            self.master.withdraw()
            self.newWindow = Toplevel(self.master)
            self.app = Window2(self.newWindow)

        else:
            self.entry_username.delete(0,"end")



class Window2:
    def __init__(self,master):
        notebook = ttk.Notebook(master)

        notebook.pack(expand = 1, fill = "both")
        #Frames
        main = ttk.Frame(notebook)

        notebook.add(main, text='Main-Screen')




if __name__ == '__main__':
    main()

Update: 30/09/2019 Is this correct?更新:30/09/2019 这是正确的吗?

def main():
    root = Tk()
    app = Window1(root)

    root.mainloop()

class Window1:
    def __init__(self,master,username): #added code
        self.username = username#added code 2

        self.master = master
        self.master.title("User Log In")
        self.master.geometry('400x150')
        self.frame = Frame(self.master)
        self.frame.pack(fill="both", expand=True)

        username = 'KOB' #added code 3
        window_1_instance = Window1(username) # added code 4

        self.label_username = Label(self.frame, text="Username: ",font=("bold",16))
        self.entry_username = Entry(self.frame, font = ("bold", 14))
        self.label_password = Label(self.frame, text="Password: ",font=("bold",16))
        self.entry_password = Entry(self.frame, show="*", font = ("bold", 14))

        self.label_username.pack()
        self.entry_username.pack()
        self.label_password.pack()
        self.entry_password.pack()

        self.logbtn = Button(self.frame, text="Login", font = ("bold", 10), command=self._login_btn_clicked)
        self.logbtn.pack()



    def _login_btn_clicked(self):
        # print("Clicked")
        username = self.entry_username.get()
        password = self.entry_password.get()

        # print(username, password)
        account_list = [line.split(":", maxsplit=1) for line in open("passwords.txt")]
        # list of 2-tuples. Usersnames with colons inside not supported.
        accounts = {key: value.rstrip() for key, value in account_list}
        # Convert to dict[username] = password, and slices off the line ending.
        # Does not support passwords ending in whitespace.
        if accounts[username] == password:
            self.master.withdraw()
            self.newWindow = Toplevel(self.master)
            self.app = Window2(self.newWindow)

        else:
            self.entry_username.delete(0,"end")



class Window2:
    def __init__(self,master):
        notebook = ttk.Notebook(master)

        notebook.pack(expand = 1, fill = "both")
        #Frames
        main = ttk.Frame(notebook)

        notebook.add(main, text='Main-Screen')

        self.User = Label(main, text=window_1_instance.username)#added code 5


if __name__ == '__main__':
    main()

Window1 is the name of the entire class. Window1是整个class的名字。 You need a single object instance of the class, and then retrieve the instance variable from within it.您需要 class 的单个 object 实例,然后从其中检索实例变量。

eg例如

class Window1:

    def __init__(self, username):
        self.username = username

...

username = 'KOB'
window_1_instance = Window1(username)

....

self.User = Label(main, text=window_1_instance.username)

In this line of your code:在这行代码中:

self.User = Label(main, text = Window1().entry_username.get())

Window1() is creating an instance of the class, the same as I did above, just without passing it to a variable. Window1()正在创建 class 的实例,与我在上面所做的相同,只是没有将其传递给变量。 Since you have defined the Window1 constructor ( __init__ method) to take master as a parameter, you would need to change this line to:由于您已定义Window1构造函数( __init__方法)以将master作为参数,因此您需要将此行更改为:

self.User = Label(main, text = Window1(master=<instance of master>).entry_username.get())

This is exactly what the error is telling you:这正是错误告诉您的内容:

TypeError: __init__() missing 1 required positional argument: 'master'

Two ways:两种方式:

  1. Directly access the value from the calling class like print(foo.x)直接访问调用 class 的值,如print(foo.x)
  2. Create a getter in the first class and call the getter from second like k = foo.getVal()在第一个 class 中创建一个吸气剂并从第二个调用吸气剂,如k = foo.getVal()

Basic example to pass value among classes with both methods:使用这两种方法在类之间传递值的基本示例:

class foo():
    def __init__(self):
        self.x = 42
    def getVal(self):
      return self.x

class bar(object):
    def __init__(self, foo):
        print(foo.x)
        k = foo.getVal()
        print(k)

a = foo()
b = bar(a)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用另一类的返回值? - How to use return value from one class in another? 如何从另一个 class 返回条目值? - How to return entry value from another class? 如何将条目的值从一个 class 传递到另一个 class? - How to pass value of Entry from one class to another class? 如何在Python中将值从一个脚本返回到另一个脚本? - How to return a value from one script to another in Python? 如何通过多重处理将布尔值从一个函数返回到另一个函数? - How to return a Boolean value from one function to another via multiprocessing? 如何将值从一个python脚本返回到另一个? - How to return a value from one python script to another? 是否可以在一个 class 中使用来自一个 object 的返回值并在另一个中使用它 - Is it possible to use a return value from one object in one class and use it in another 如何将变量值从一个文件中的一个类传递到另一个文件中的另一个类 python tkinter - How to pass variable value from one class in one file to another class in another file python tkinter 从一个python脚本返回值到另一个 - return value from one python script to another PyQt:将值从一个类传递给另一个类 - PyQt: pass the value from one class to another
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM