简体   繁体   English

使用从一个 class 到另一个 tkinter 的变量

[英]Using a variable from one class to another tkinter

Here is the full code for test please run it and tell me if I can store username and password outside the class after destroy the frame这是测试的完整代码,请运行它并告诉我是否可以在销毁框架后将用户名和密码存储在 class 之外

import tkinter as tk
    from tkinter import *
    from PIL import Image, ImageTk
    from tkinter import filedialog
    

class SampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self._frame = None
        self.title('Instagram Bot')
        self.geometry("500x500")
        self.switch_frame(StartPage)

    def switch_frame(self, frame_class):
        """Destroys current frame and replaces it with a new one."""
        new_frame = frame_class(self)
        if self._frame is not None:
            self._frame.destroy()
        self._frame = new_frame
        self._frame.pack()



class StartPage(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        tk.Label(self, text="Enter Username").pack(side="top", fill="x", pady=10)
        self.username = tk.Entry(self,)
        self.username.pack()
        tk.Label(self, text='Enter Pssword').pack(side='top', fill='x', pady=10)
        self.password = tk.Entry(self)
        self.password.pack()
        self.password = self.password.get()
        self.username = self.username.get()
        # if(username.get('text') == None or password.get('text') == None):
        #     tk.Button(self, text="Login",
        #           command=lambda: master.switch_frame(StartPage)).pack()
        # else:
        
        tk.Button(self, text="Login", command=lambda: master.switch_frame(PageOne) and login_data()).pack()


class PageOne(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        tk.Label(self, text="Welcome").pack(side="top", fill="x", pady=10)
        tk.Button(self, text='Some text', command=lambda: master.switch_frame(Hashtag_page)).pack()

    def  __init__(self, master):
        tk.Frame.__init__(self, master)
        self.hastag_lbl = tk.Label(self, text='Choice file')
        self.hastag_lbl.pack(side='top',fill='x',pady=10)
        tk.Button(self, text='browse', command=self.browseFiles_hstg).pack()
        tk.Button(self, text='Start Bot', command=self.start_hashtag).pack()

        
    
    def browseFiles_hstg(self): 
        filename = filedialog.askopenfilename(initialdir = "/", 
                                          title = "Select a File", 
                                          filetypes = (("Text files", 
                                                        "*.txt*"), 
                                                       ("all files", 
                                                        "*.*"))) 
        # Change label contents 
        self.hastag_lbl.configure(text = filename)


    def start_hashtag(self):
        print(StartPage.username, StartPage.password)






if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python3.6/tkinter/ init .py", line 1705, in call return self.func(*args) File "scofrlw.py", line 71, in start_hashtag print(StartPage.username, StartPage.password) AttributeError: type object 'StartPage' has no attribute 'username' Tkinter 回调 Traceback(最近一次调用最后一次)中的异常:文件“/usr/lib/python3.6/tkinter/init .py”,第 1705 行,调用中返回self.func (*args) 文件“scofrlw.py”,第 71 行,在 start_hashtag print(StartPage.username, StartPage.password) AttributeError: type object 'StartPage' has no attribute 'username'


I would make a dictionary of the username and password, but depending on your GUI, I don't know the best option for you我会制作用户名和密码的字典,但根据您的 GUI,我不知道最适合您的选择

Make the dictionary制作字典

dictionary = {}

class StartPage(tk.Frame):
   ...

Add values for the username and password.添加用户名和密码的值。

def login_credentials(self):
    dictionary['password'] = self.password.get()
    dictionary['username'] = self.username.get()

Then you can just print them然后你可以打印它们

def start_hashtag(self):
    print(dictionary['username'],dictionary['password'])

In the code below, i have been storing the credentials inside the master (SampleApp) which is accessible from your class PageOne aswell.在下面的代码中,我一直将凭据存储在主 (SampleApp) 中,该凭据也可以从您的 class PageOne 访问。

Alternatively, you may consider storing the credentials in a dict, and passing it to your PageOne during initialization.或者,您可以考虑将凭据存储在 dict 中,并在初始化期间将其传递给 PageOne。

import tkinter as tk
from tkinter import *
#from PIL import Image, ImageTk
from tkinter import filedialog


class SampleApp(tk.Tk):
    def __init__(self):
        self.test = "I am the MasterAPP"
        tk.Tk.__init__(self)
        self._frame = None
        self.title('Instagram Bot')
        self.geometry("500x500")
        self.switch_frame(StartPage)

        self.username = None
        self.password = None

    def switch_frame(self, frame_class):
        """Destroys current frame and replaces it with a new one."""
        new_frame = frame_class(self)
        if self._frame is not None:
            self._frame.destroy()
        self._frame = new_frame
        self._frame.pack()



class StartPage(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        tk.Label(self, text="Enter Username").pack(side="top", fill="x", pady=10)
        self.username = tk.Entry(self,)
        self.username.pack()
        tk.Label(self, text='Enter Pssword').pack(side='top', fill='x', pady=10)
        self.password = tk.Entry(self)
        self.password.pack()


        tk.Button(self, text="Login",
            command=lambda:
                self.login()
        ).pack()


    def login(self):
        self.save_credentials()
        self.master.switch_frame(PageOne)


    def save_credentials(self):
        self.master.password = self.password.get()
        self.master.username = self.username.get()




class PageOne(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        tk.Label(self, text="Welcome").pack(side="top", fill="x", pady=10)
        tk.Button(self, text='Some text', command=lambda: master.switch_frame(Hashtag_page)).pack()

    def  __init__(self, master):
        tk.Frame.__init__(self, master)
        self.hastag_lbl = tk.Label(self, text='Choice file')
        self.hastag_lbl.pack(side='top',fill='x',pady=10)
        tk.Button(self, text='browse', command=self.browseFiles_hstg).pack()
        tk.Button(self, text='Start Bot', command=self.start_hashtag).pack()



    def browseFiles_hstg(self):
        filename = filedialog.askopenfilename(initialdir = "/",
                                          title = "Select a File",
                                          filetypes = (("Text files",
                                                        "*.txt*"),
                                                       ("all files",
                                                        "*.*")))
        # Change label contents
        self.hastag_lbl.configure(text = filename)


    def start_hashtag(self):
        print(self.master.username, self.master.password)






if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

There are few issues in your code:您的代码中有几个问题:

  • should not call self.password = self.password.get() and self.username = self.username.get() just after self.username and self.password are created because they will be both empty strings and override the references to the two Entry widgets.不应在创建self.usernameself.password之后调用self.password = self.password.get()self.username = self.username.get()因为它们都是空字符串并覆盖对两个Entry小部件。

  • username and password are instance variables of StartPage , so they cannot be access by StartPage.username and StartPage.password usernamepasswordStartPage的实例变量,因此不能通过StartPage.usernameStartPage.password访问

  • two __init__() function definitions in PageOne class PageOne class 中的两个__init__() function 定义

  • when switching frame, the previous frame is destroyed.切换帧时,前一帧被破坏。 So username and password will be destroyed as well and cannot be accessed anymore.所以usernamepassword也将被销毁,无法再访问。

You can use instance of SampleApp to store the username and password , so they can be accessed by its child frames:您可以使用SampleApp的实例来存储usernamepassword ,以便其子框架可以访问它们:

class StartPage(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        tk.Label(self, text="Enter Username").pack(side="top", fill="x", pady=10)
        self.username = tk.Entry(self,)
        self.username.pack()
        tk.Label(self, text='Enter Pssword').pack(side='top', fill='x', pady=10)
        self.password = tk.Entry(self)
        self.password.pack()
        tk.Button(self, text="Login", command=self.login).pack()

    def login(self):
        # store the username and password in instance of 'SampleApp'
        self.master.username = self.username.get()
        self.master.password = self.password.get()
        # switch to PageOne
        self.master.switch_frame(PageOne)

class PageOne(tk.Frame):
    def  __init__(self, master):
        tk.Frame.__init__(self, master)
        self.hastag_lbl = tk.Label(self, text='Choice file')
        self.hastag_lbl.pack(side='top',fill='x',pady=10)
        tk.Button(self, text='browse', command=self.browseFiles_hstg).pack()
        tk.Button(self, text='Start Bot', command=self.start_hashtag).pack()
    
    def browseFiles_hstg(self): 
        filename = filedialog.askopenfilename(initialdir = "/", 
                                              title = "Select a File", 
                                              filetypes = (("Text files", 
                                                            "*.txt*"), 
                                                           ("all files", 
                                                            "*.*"))) 
        # Change label contents
        if filename:
            self.hastag_lbl.configure(text = filename)

    def start_hashtag(self):
        # get username and password from instance of SampleApp
        print(self.master.username, self.master.password)

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

相关问题 如何使用 tkinter 从另一个 class 修改一个 class 中使用的变量? - How can I modify a variable being used in one class from another class by using tkinter? 如何将变量值从一个文件中的一个类传递到另一个文件中的另一个类 python tkinter - How to pass variable value from one class in one file to another class in another file python tkinter 使用.get()从另一个类中提取Tkinter变量 - Using .get() to pull a Tkinter variable from another class 如何使用tkinter在python中将数据从一个类传输到另一个类? - How to transfer data from one class to another in python using tkinter? 从另一个类将变量插入Tkinter列表框 - Inserting a Variable into Tkinter Listbox from Another Class 将 Tkinter 变量从一个 function 传递到另一个 - Passing Tkinter variable from one function to another Tkinter:如何将变量从一个 class(窗口)传递到另一个 class(窗口)-(不是顶层框架)? - Tkinter: how to pass variable from one class (window) to another class (window) - (not toplevel frame)? 另一个类中的tkinter变量 - tkinter variable in another class 使用从一个 class 到另一个 python 中的变量 - Using a variable from one class to another one in python 在另一个 Tkinter 类的一个 Tkinter 类中编辑/添加 Tkinter 小部件 - Edit/add Tkinter widget in one Tkinter class from another Tkinter class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM