[英]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.username
和self.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
username
和password
是StartPage
的实例变量,因此不能通过StartPage.username
和StartPage.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.所以
username
和password
也将被销毁,无法再访问。
You can use instance of SampleApp
to store the username
and password
, so they can be accessed by its child frames:您可以使用
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.