【问题标题】:Using a variable from one class to another tkinter使用从一个类到另一个 tkinter 的变量
【发布时间】:2020-11-30 17:51:39
【问题描述】:

这是完整的测试代码,请运行它并告诉我是否可以在销毁框架后将用户名和密码存储在类外

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()

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


【问题讨论】:

  • 请格式化您的代码以便我们可以运行它
  • 解决方案取决于您如何管理多个框架。 switch_frame 中的注释暗示您将在创建 Hashtag_page 时销毁 StartPage。如果是这种情况,您将无法获得价值。请提供一个minimal reproducible example 我们可以实际运行。
  • 我可以将值存储在全局或 StartPage 之外的某个地方,我将更改为可以运行
  • 你应该在编码之前规划你的 GUI,如果你没有。是的,你可以存储一个全局变量
  • 我用全局更新了我尝试的代码,但我没有得到结果

标签: python class tkinter


【解决方案1】:

在下面的代码中,我将凭据存储在主 (SampleApp) 中,您的课程 PageOne 也可以访问该凭据。

或者,您可以考虑将凭据存储在 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()

【讨论】:

    【解决方案2】:

    我会制作一个包含用户名和密码的字典,但根据您的 GUI,我不知道最适合您的选择

    制作字典

    dictionary = {}
    
    class StartPage(tk.Frame):
       ...
    

    为用户名和密码添加值。

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

    然后你就可以打印它们了

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

    【讨论】:

    • 我得到空变量可能来自 tkinter
    【解决方案3】:

    您的代码中存在一些问题:

    • 不应在创建self.username 和self.password 之后调用self.password = self.password.get() 和self.username = self.username.get(),因为它们都是空字符串并覆盖对两个Entry 小部件的引用。

    • username和password是StartPage的实例变量,所以StartPage.username和StartPage.password不能访问它们

    • PageOne 类中的两个__init__() 函数定义

    • 切换帧时,前一帧被销毁。所以username 和password 也将被销毁,无法再访问。

    您可以使用SampleApp 的实例来存储username 和password,以便它们的子框架可以访问它们:

    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)
    

    【讨论】:

      猜你喜欢
      • 2020-03-07
      • 2013-09-17
      • 2021-04-08
      • 2016-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-08
      相关资源
      最近更新 更多