问题描述
问题:
我有 2 个类似的 tkinter 窗口,我想对其进行压缩或模块化(因为我有几乎 2 个完全相同的功能),这将使代码更紧凑且更易于阅读(有 2 个的意义何在?如果我可以只有一个功能?).
I have 2 similar tkinter windows, which I would like to condense or modularise (because i have pretty much 2 of the exact same function), which would make the code more compact and more easily readable (whats the point of having 2 functions if i could have just one?).
我该怎么做,我应该使用类还是函数?
How would i do this and should i use a class or a function?
代码:
from tkinter import *
import sys
def register_normal():
window1=Tk()
window1.title('Registration')
window1.geometry('300x300')
def register(*args):
print('This works aswell!')
label_hidden=Label(window1, text="")
photo1=PhotoImage(file='registration.png')
photo_label1=Label(window1, image=photo1)
label_hidden_1=Label(window1,text="")
new_username_label=Label(window1,text='NEW USERNAME',font=('arial', 10, 'bold'))
login_username=Entry(window1, width=40)
label_hidden_2=Label(window1,text="")
new_password_label=Label(window1,text='NEW MASTER PASSWORD',font=('arial', 10, 'bold'))
login_password=Entry(window1,width=40, show='*')
label_hidden_3=Label(window1,text="")
login_btn=Button(window1,text='REGISTER',width=20,height=1,font=('arial', 10, 'bold'), command=register)
login_password.bind('<Return>', register)
label_hidden_1.pack()
photo_label1.pack()
label_hidden.pack()
new_username_label.pack()
login_username.pack()
label_hidden_2.pack()
new_password_label.pack()
login_password.pack()
label_hidden_3.pack()
login_btn.pack()
window1.mainloop()
def login_normal():
window2=Tk()
window2.title('Email Manager')
window2.geometry('300x300')
def login(*args):
print('This works!')
label_hidden=Label(window2, text="")
photo2=PhotoImage(file='email.png')
photo_label2=Label(window2, image=photo2)
label_hidden_1=Label(window2,text="")
username_lable=Label(window2,text='USERNAME',font=('arial', 10, 'bold'))
login_username=Entry(window2, width=40)
label_hidden_2=Label(window2,text="")
password_lable=Label(window2,text='MASTER PASSWORD',font=('arial', 10, 'bold'))
login_password=Entry(window2,width=40, show='*')
label_hidden_3=Label(window2,text="")
login_btn=Button(window2,text='LOGIN',width=20,height=1,font=('arial', 10, 'bold'), command=login)
login_password.bind('<Return>', login)
label_hidden_1.pack()
photo_label2.pack()
label_hidden.pack()
username_lable.pack()
login_username.pack()
label_hidden_2.pack()
password_lable.pack()
login_password.pack()
label_hidden_3.pack()
login_btn.pack()
window2.mainloop()
def main():
register_normal()
login_normal()
if __name__ == '__main__':
main()
#===================================icons-and-pictures-author-attribute======================================#
#===========Icons made by "https://www.freepik.com" "Freepik" from "https://www.flaticon.com/" ==============#
#===================================icons-and-pictures-author-attribute======================================#
推荐答案
我会给你一个例子,你可以使用模板然后编辑值,我使用的是框架,它可以是按下不同按钮时升高.
I will give you an example where you can use a template and then edit the values, I am using frames, which can be raised when pressed upon different button.
from tkinter import *
class Form(Frame):
def __init__(self,master,user_txt,img,pw_txt,btn_txt,callback,*args,**kwargs):
Frame.__init__(self,master,*args,**kwargs)
self.photo1 = PhotoImage(file=img)
Label(self, image=self.photo1).pack()
Label(self,text=user_txt,font=('arial', 10, 'bold')).pack(pady=(50,0))
self.e1 = Entry(self, width=40) # self because later needs to be accessed
self.e1.pack(pady=(0,15))
Label(self,text=pw_txt,font=('arial', 10, 'bold')).pack()
self.e2 = Entry(self,width=40, show='*')
self.e2.pack(pady=(0,15))
login_btn = Button(self,text=btn_txt,width=20,height=1,font=('arial', 10, 'bold'), command=callback)
self.e2.bind('<Return>', lambda e: callback())
login_btn.pack(pady=(0,50))
def log(pg, e=None): # Do your password check and other stuff
print('Username: ', pg.e1.get())
print('Password: ', pg.e2.get())
def reg(pg, e=None):
print('Reg Username: ', pg.e1.get())
print('Reg Password: ', pg.e2.get())
if __name__ == '__main__':
root = Tk()
register = Form(root,'NEW USERNAME',None,'NEW MASTER PASSWORD','REGISTER',lambda: reg(register))
login = Form(root,'USERNAME',None,'MASTER PASSWORD','LOGIN',lambda: log(login))
Button(root,text='Switch to register page',command=lambda: register.tkraise()).grid(row=1,column=0) # To raise register frame
Button(root,text='Switch to login page',command=lambda: login.tkraise()).grid(row=2,column=0)
register.grid(row=0,column=0) # Place in same place so can be raised with tkraise()
login.grid(row=0,column=0)
root.mainloop()
我删除了空白标签并使用 pady=(up,down)
来推标签上下.我使用了类而不是函数,因为它是可实例化的.这个使用框架的例子也将摆脱创建更多的窗口(更现代).
I have removed the blank labels and used pady=(up,down)
to push the labels up and down. I have used classes instead of a function as it is instantiable. This example using frames will also get rid of creating more windows(more modern).
正如你所看到的,这只是一个例子,因为一个注册表单需要2个密码框(确认密码也是如此),尝试仅将这种方法用于相似的概念,登录和注册是不同的功能,因此它们的表单应该也长得不一样.您只需创建一个名为Login
的类,然后从Frame
继承并将其放置在屏幕上,就像这里一样,与Registration
相同.使用它的一个很好的例子是用户的个人资料,模板对所有用户都是相同的,只有用户数据会有所不同,这些数据将作为变量传递.
As you can see this is just a mere example because, a register form would need 2 password boxes(confirm password also), try to use this approach for similar concepts only, login and registration are different functions and hence their forms should also look different. You would just create a class called Login
and then inherit from Frame
and place it on the screen just like here, same with Registration
. A good example of where to use this is a profile of a user, the template would be same for all users and only the user data would vary, which would be passed as variables.
为了更好地理解,请阅读:
For better understanding, read:
Tkinter:AttributeError:NoneType 对象没有属性
PEP 8 -- Python 代码风格指南 |Python.org
这篇关于如何使 2 个 tkinter 窗口的 2 个功能更加简洁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!