Python Py 3:tkinter帧,在帧类内部或外部编码
因此,我正在使用Python3和tkinter为学校创建一个GUI数学程序,在这个程序中,我们必须询问用户想要使用什么公式(加法、减法、乘法、除法),然后问10个问题,在该页面上回答完所有10个问题后,显示一个结果页面,然后在循环中重新开始。我想创造4种不同的困难 简单=介于(1,9)之间的范围,中等=介于(10,24)之间的范围,硬=介于(25,50)之间的范围,疯狂=介于(51100)之间的范围 到目前为止,我已经创建了如下所示的gui,但我想知道我是要在page类中还是在类之外组织公式的计算。我对python/tkinter还很陌生,我以前从未使用过它,但我刚刚从youtube上学到了很多东西,花了好几个小时看了 我想知道的是,从现在开始,在哪里放置方程代码/公式。一旦我知道该把它放在哪里,我就会离开 (如果您复制并粘贴到Python3中并保存,下面的所有代码都将立即生效。由于我是如何将所有代码复制到聊天中的,因此复制和粘贴过程中出现的任何问题都将是缩进。) 你在下面看到的任何问题,请随时指出。正如我说的,我是一个新手,谷歌并没有帮上什么忙,因为我不知道输入什么才能找到它 问候Python Py 3:tkinter帧,在帧类内部或外部编码,python,class,user-interface,python-3.x,tkinter,Python,Class,User Interface,Python 3.x,Tkinter,因此,我正在使用Python3和tkinter为学校创建一个GUI数学程序,在这个程序中,我们必须询问用户想要使用什么公式(加法、减法、乘法、除法),然后问10个问题,在该页面上回答完所有10个问题后,显示一个结果页面,然后在循环中重新开始。我想创造4种不同的困难 简单=介于(1,9)之间的范围,中等=介于(10,24)之间的范围,硬=介于(25,50)之间的范围,疯狂=介于(51100)之间的范围 到目前为止,我已经创建了如下所示的gui,但我想知道我是要在page类中还是在类之外组织公式的计
import tkinter as tk
from tkinter import *
from tkinter import ttk #css kind of thing for tkinter
import random
difficulty = []
LARGE_FONT = ("Times New Roman", 25)
MEDIUM_FONT = ("Times New Roman", 15)
SMALL_FONT = ("Times New Roman", 10)
###Base Code For Pages
class ourprogramclass(tk.Tk):
def __init__ (self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.iconbitmap(self, default="mathsicon.ico")
tk.Tk.wm_title(self, "Mathematic Equation program")
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, AdditionPage, SubtractionPage, MultiplicationPage, DivisionPage ):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(StartPage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
###Page Classes front page
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
label1 = tk.Label(self, text = "Mathmatics Problems Quiz", font=LARGE_FONT)
label2 = tk.Label(self, text = "Mathematic Equation program", font=MEDIUM_FONT)
label3 = tk.Label(self, text = "Select Your Operation and Difficulty Level", font=SMALL_FONT)
label1.pack(pady=10,padx=10)
label2.pack(pady=10,padx=10)
label3.pack(pady=10,padx=10)
button1 = tk.Button(self, text = "Addition Equations", font=MEDIUM_FONT,command=lambda: controller.show_frame(AdditionPage)).pack(fill=X)
label = Label(self,text="").pack()
button2 = tk.Button(self, text = "Subtraction Equations", font=MEDIUM_FONT,command=lambda: controller.show_frame(SubtractionPage)).pack(fill=X)
label = Label(self,text="").pack()
button3 = tk.Button(self, text = "Multiplication Equations", font=MEDIUM_FONT,command=lambda: controller.show_frame(MultiplicationPage)).pack(fill=X)
label = Label(self,text="").pack()
button4 = tk.Button(self, text = "Division Equations", font=MEDIUM_FONT,command=lambda: controller.show_frame(DivisionPage)).pack(fill=X)
label = Label(self,text="").pack()
label4 = tk.Label(self, text = "Select Difficulty", font=LARGE_FONT).pack()
def checkbutton_value1():
if (var1.get()):
var2.set(0)
var3.set(0)
var4.set(0)
del difficulty[:]
difficulty.append(1)
print (difficulty[0])
def checkbutton_value2():
if(var2.get()):
var1.set(0)
var3.set(0)
var4.set(0)
del difficulty[:]
difficulty.append(2)
print (difficulty[0])
def checkbutton_value3():
if(var3.get()):
var1.set(0)
var2.set(0)
var4.set(0)
del difficulty[:]
difficulty.append(3)
print (difficulty[0])
def checkbutton_value4():
if(var4.get()):
var1.set(0)
var2.set(0)
var3.set(0)
del difficulty[:]
difficulty.append(4)
print (difficulty[0])
var1 = IntVar()
dif_button1 = tk.Checkbutton(self, text="Easy", variable=var1, command=checkbutton_value1).pack()
var2 = IntVar()
dif_button2 = tk.Checkbutton(self, text="Medium", variable=var2, command=checkbutton_value2).pack()
var3 = IntVar()
dif_button3 = tk.Checkbutton(self, text="Hard ", variable=var3, command=checkbutton_value3).pack()
var4 = IntVar()
dif_button4 = tk.Checkbutton(self, text="Insane", variable=var4, command=checkbutton_value4).pack()
quit_button = tk.Button(self, text='Quit', command=quit, font=MEDIUM_FONT).pack(fill=X, side = BOTTOM)
###Addition Page
class AdditionPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
label1 = tk.Label(self, text = "Mathmatics Problems Quiz", font=LARGE_FONT).pack(pady=10,padx=10)
label2 = tk.Label(self, text = "Mathematic Equation program", font=MEDIUM_FONT).pack(pady=10,padx=10)
label3 = tk.Label(self, text = "You have Selected Addition as The Unit", font=SMALL_FONT).pack(pady=10,padx=10)
button1 = tk.Button(self, text = "Reselect Unit", font=MEDIUM_FONT,command=lambda: controller.show_frame(StartPage)).pack(fill=X)
label = Label(self,text="").pack()
label = Label(self,text="").pack()
#-----THIS IS WHERE I WANT THE EQUATION TO SHOW IN THE LABEL BELOW-----#
question_label = Label(self, text="Enter Your Answer", font=MEDIUM_FONT ).pack()
label = Label(self,text="").pack()
self.entrytext = StringVar()
Entry(self, textvariable=self.entrytext, font=MEDIUM_FONT,).pack(fill=X)
label = Label(self,text="").pack()
label = Label(self,text="").pack()
submit_button = tk.Button(self, text = "Submit Answer", font=MEDIUM_FONT).pack(fill=X)
quit_button = tk.Button(self, text='Quit', command=quit, font=MEDIUM_FONT,).pack(fill=X, side = BOTTOM)
####Subtraction Page
class SubtractionPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
label1 = tk.Label(self, text = "Mathmatics Problems Quiz", font=LARGE_FONT).pack(pady=10,padx=10)
label2 = tk.Label(self, text = "Mathematic Equation program", font=MEDIUM_FONT).pack(pady=10,padx=10)
label3 = tk.Label(self, text = "You have Selected Subtraction as The Unit", font=SMALL_FONT).pack(pady=10,padx=10)
button1 = tk.Button(self, text = "Reselect Unit", font=MEDIUM_FONT,command=lambda: controller.show_frame(StartPage)).pack(fill=X)
label = Label(self,text="").pack()
label = Label(self,text="").pack()
#-----THIS IS WHERE I WANT THE EQUATION TO SHOW IN THE LABEL BELOW-----#
question_label = Label(self, text="Enter Your Answer", font=MEDIUM_FONT ).pack()
label = Label(self,text="").pack()
self.entrytext = StringVar()
Entry(self, textvariable=self.entrytext, font=MEDIUM_FONT,).pack(fill=X)
label = Label(self,text="").pack()
label = Label(self,text="").pack()
submit_button = tk.Button(self, text = "Submit Answer", font=MEDIUM_FONT).pack(fill=X)
quit_button = tk.Button(self, text='Quit', command=quit, font=MEDIUM_FONT,).pack(fill=X, side = BOTTOM)
###Multiply Page
class MultiplicationPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
label1 = tk.Label(self, text = "Mathmatics Problems Quiz", font=LARGE_FONT).pack(pady=10,padx=10)
label2 = tk.Label(self, text = "Mathematic Equation program", font=MEDIUM_FONT).pack(pady=10,padx=10)
label3 = tk.Label(self, text = "You have Selected Multiplication as The Unit", font=SMALL_FONT).pack(pady=10,padx=10)
button1 = tk.Button(self, text = "Reselect Unit", font=MEDIUM_FONT,command=lambda: controller.show_frame(StartPage)).pack(fill=X)
label = Label(self,text="").pack()
label = Label(self,text="").pack()
#-----THIS IS WHERE I WANT THE EQUATION TO SHOW IN THE LABEL BELOW-----#
question_label = Label(self, text="Enter Your Answer", font=MEDIUM_FONT ).pack()
label = Label(self,text="").pack()
self.entrytext = StringVar()
Entry(self, textvariable=self.entrytext, font=MEDIUM_FONT,).pack(fill=X)
label = Label(self,text="").pack()
label = Label(self,text="").pack()
submit_button = tk.Button(self, text = "Submit Answer", font=MEDIUM_FONT).pack(fill=X)
quit_button = tk.Button(self, text='Quit', command=quit, font=MEDIUM_FONT,).pack(fill=X, side = BOTTOM)
###Division Page
class DivisionPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
label1 = tk.Label(self, text = "Mathmatics Problems Quiz", font=LARGE_FONT).pack(pady=10,padx=10)
label2 = tk.Label(self, text = "Mathematic Equation program", font=MEDIUM_FONT).pack(pady=10,padx=10)
label3 = tk.Label(self, text = "You have Selected Division as The Unit", font=SMALL_FONT).pack(pady=10,padx=10)
button1 = tk.Button(self, text = "Reselect Unit", font=MEDIUM_FONT,command=lambda: controller.show_frame(StartPage)).pack(fill=X)
label = Label(self,text="").pack()
label = Label(self,text="").pack()
#-----THIS IS WHERE I WANT THE EQUATION TO SHOW IN THE LABEL BELOW-----#
question_label = Label(self, text="Enter Your Answer", font=MEDIUM_FONT ).pack()
label = Label(self,text="").pack()
self.entrytext = StringVar()
Entry(self, textvariable=self.entrytext, font=MEDIUM_FONT,).pack(fill=X)
label = Label(self,text="").pack()
label = Label(self,text="").pack()
submit_button = tk.Button(self, text = "Submit Answer", font=MEDIUM_FONT).pack(fill=X)
quit_button = tk.Button(self, text='Quit', command=quit, font=MEDIUM_FONT,).pack(fill=X, side = BOTTOM)
app = ourprogramclass()
app.mainloop()
首先,难度选择的复选按钮所携带的逻辑可以被单选按钮所取代,这将减少很多代码 其次,您可以将四个等式页面共享的逻辑提取到一个基类中,并继承该基类来创建四个等式页面 至于你的问题,我认为它可以放在基类的某个方法中,这是我修改的代码 这本书[Programming Python]非常好地介绍了tkinter,本网站提供了tk的详细信息
import tkinter as tk
from tkinter import *
from tkinter import ttk #css kind of thing for tkinter
import random
dif_enum = ['Easy', 'Medium', 'Hard', 'Insane']
current_difficulty = dif_enum[0]
NUM_QUESTIONS = 10
LARGE_FONT = ("Times New Roman", 25)
MEDIUM_FONT = ("Times New Roman", 15)
SMALL_FONT = ("Times New Roman", 10)
###Base Code For Pages
class ourprogramclass(tk.Tk):
def __init__ (self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
# tk.Tk.iconbitmap(self, default="mathsicon.ico")
tk.Tk.wm_title(self, "Mathematic Equation program")
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, AdditionPage, SubtractionPage, MultiplicationPage, DivisionPage ):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(StartPage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
###Page Classes front page
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
label1 = tk.Label(self, text = "Mathmatics Problems Quiz", font=LARGE_FONT)
label2 = tk.Label(self, text = "Mathematic Equation program", font=MEDIUM_FONT)
label3 = tk.Label(self, text = "Select Your Operation and Difficulty Level", font=SMALL_FONT)
label1.pack(pady=10,padx=10)
label2.pack(pady=10,padx=10)
label3.pack(pady=10,padx=10)
button1 = tk.Button(self, text = "Addition Equations", font=MEDIUM_FONT,command=lambda: controller.show_frame(AdditionPage)).pack(fill=X)
label = Label(self,text="").pack()
button2 = tk.Button(self, text = "Subtraction Equations", font=MEDIUM_FONT,command=lambda: controller.show_frame(SubtractionPage)).pack(fill=X)
label = Label(self,text="").pack()
button3 = tk.Button(self, text = "Multiplication Equations", font=MEDIUM_FONT,command=lambda: controller.show_frame(MultiplicationPage)).pack(fill=X)
label = Label(self,text="").pack()
button4 = tk.Button(self, text = "Division Equations", font=MEDIUM_FONT,command=lambda: controller.show_frame(DivisionPage)).pack(fill=X)
label = Label(self,text="").pack()
label4 = tk.Label(self, text = "Select Difficulty", font=LARGE_FONT).pack()
# @etuc_comment:Use `Radiobutton` for the "select one from many" logic. It takes only a few lines.
difficulty = tk.StringVar(value=dif_enum[0])
def show_and_set_difficulty():
global current_difficulty
current_difficulty = difficulty.get()
print(1 + dif_enum.index(difficulty.get()), difficulty.get())
for dif in dif_enum:
tk.Radiobutton(self, text=dif, value=dif, variable=difficulty, command=show_and_set_difficulty).pack()
quit_button = tk.Button(self, text='Quit', command=quit, font=MEDIUM_FONT).pack(fill=X, side = BOTTOM)
class EquationPageBase(tk.Frame):
def __init__(self, parent, controller, equal_type):
tk.Frame.__init__(self,parent)
tk.Label(self, text="Mathmatics Problems Quiz", font=LARGE_FONT).pack(pady=10,padx=10)
tk.Label(self, text="Mathematic Equation program", font=MEDIUM_FONT).pack(pady=10,padx=10)
# @etuc_comment: Use the third parameter `equal_type` for displaying current equation type.
tk.Label(self, text="You have Selected {} as The Unit".format(equal_type), font=SMALL_FONT).pack(pady=10,padx=10)
tk.Button(self, text="Reselect Unit", font=MEDIUM_FONT,command=lambda: controller.show_frame(StartPage)).pack(fill=X)
Label(self,text="").pack()
Label(self,text="").pack()
#-----THIS IS WHERE I WANT THE EQUATION TO SHOW IN THE LABEL BELOW-----#
self.submit_counter = 0
self.correct_counter = 0
self.equation_strvar = tk.StringVar(value='')
Label(self, textvariable=self.equation_strvar, font=MEDIUM_FONT).pack()
Label(self,text="").pack()
self.answer_strvar = StringVar()
Entry(self, textvariable=self.answer_strvar, font=MEDIUM_FONT, ).pack(fill=X)
Label(self,text="").pack()
Label(self,text="").pack()
tk.Button(self, text="Submit Answer", font=MEDIUM_FONT, command=self.submit).pack(fill=X)
tk.Button(self, text='Quit', command=quit, font=MEDIUM_FONT,).pack(fill=X, side = BOTTOM)
self.update_equation()
def update_equation(self):
self.equation = self.gen_equal()
self.equation_strvar.set('Enter Your Answer For: {}'.format(self.equation))
self.answer_strvar.set('')
def gen_equal(self):
"""
Subclasses will overload this method to generate the proper equation according to difficulty and
equation type setting. See an example in the `AdditionPage`
:return: Should return the equation as string. e.g. "1 + 2"
"""
pass
def submit(self):
try:
user_answer = int(self.answer_strvar.get())
except:
return
if eval(self.equation) == user_answer:
print('Correct')
self.correct_counter += 1
else:
print('Error: {} != {}, answer is {}'.format(self.equation, user_answer, eval(self.equation)))
self.submit_counter += 1
if self.submit_counter < NUM_QUESTIONS:
self.update_equation()
else:
self.show_result()
self.submit_counter = 0
self.correct_counter = 0
def show_result(self):
print('{} questions, {} correct.'.format(NUM_QUESTIONS, self.correct_counter))
# Addition Page
class AdditionPage(EquationPageBase):
def __init__(self, parent, controller):
EquationPageBase.__init__(self, parent, controller, equal_type='Addition')
def gen_equal(self):
"""
This is an example for addition.
"""
if current_difficulty == 'Easy':
return '{} + {}'.format(random.randint(1, 10), random.randint(1, 10))
elif current_difficulty == 'Medium':
return '{} + {}'.format(random.randint(10, 25), random.randint(10, 25))
elif current_difficulty == 'Hard':
return '{} + {}'.format(random.randint(25, 50), random.randint(25, 50))
elif current_difficulty == 'Insane':
return '{} + {}'.format(random.randint(50, 100), random.randint(50, 100))
else:
raise ValueError('Wrong difficulty')
# Subtraction Page
class SubtractionPage(EquationPageBase):
def __init__(self, parent, controller):
EquationPageBase.__init__(self, parent, controller, equal_type='Subtraction')
def gen_equal(self):
pass
# Multiply Page
class MultiplicationPage(EquationPageBase):
def __init__(self, parent, controller):
EquationPageBase.__init__(self, parent, controller, equal_type='Multiplication')
def gen_equal(self):
pass
# Division Page
class DivisionPage(EquationPageBase):
def __init__(self, parent, controller):
EquationPageBase.__init__(self, parent, controller, equal_type='Division')
def gen_equal(self):
pass
app = ourprogramclass()
app.mainloop()
将tkinter作为tk导入
从tkinter进口*
从tkinter导入ttk#css之类的东西
随机输入
dif_enum=[“简单”、“中等”、“困难”、“疯狂”]
当前难度=dif_枚举[0]
问题数量=10
大字体=(“新罗马时代”,25)
中字体=(“泰晤士报新罗马”,15)
小字体=(“新罗马时代”,10)
###页面的基本代码
类或类(tk.tk):
定义初始化(self,*args,**kwargs):
tk.tk.\uuuuu初始化(self,*args,**kwargs)
#tk.tk.iconbitmap(self,default=“mathsicon.ico”)
tk.tk.wm_标题(self,“数学方程程序”)
容器=tk.框架(自身)
container.pack(side=“top”,fill=“both”,expand=True)
container.grid_rowconfigure(0,权重=1)
container.grid\u column配置(0,权重=1)
self.frames={}
对于F in(起始页、加法页、减法页、乘法页、分区页):
框架=F(容器,自身)
self.frames[F]=帧
frame.grid(行=0,列=0,sticky=“nsew”)
自显示帧(起始页)
def显示画面(自身,续):
帧=自身帧[续]
frame.tkraise()
###页面类首页
类起始页(传统框架):
定义初始化(自、父、控制器):
tk.Frame.\uuuu init\uuuuu(自,父)
label1=tk.Label(self,text=“数学问题测验”,font=LARGE\u font)
label2=tk.Label(self,text=“数学方程程序”,font=MEDIUM\u font)
label3=tk.Label(self,text=“选择您的操作和难度级别”,font=SMALL\u font)
标签1.包装(pady=10,padx=10)
标签2.包装(pady=10,padx=10)
标签3.包装(pady=10,padx=10)
button1=tk.Button(self,text=“Addition Equations”,font=MEDIUM\u font,command=lambda:controller.show\u frame(AdditionPage)).pack(fill=X)
标签=标签(self,text=”“).pack()
button2=tk.Button(self,text=“减法方程”,font=MEDIUM\u font,command=lambda:controller.show\u frame(减法页)).pack(fill=X)
标签=标签(self,text=”“).pack()
button3=tk.Button(self,text=“乘法方程”,font=MEDIUM\u font,command=lambda:controller.show\u frame(乘法页面)).pack(fill=X)
标签=标签(self,text=”“).pack()
button4=tk.Button(self,text=“Division Equations”,font=MEDIUM\u font,command=lambda:controller.show\u frame(Division page)).pack(fill=X)
标签=标签(self,text=”“).pack()
label4=tk.Label(self,text=“选择难度”,font=LARGE\u font).pack()
#@etuc_comment:Radiobutton用于“从多个选项中选择一个”逻辑。它只需要几行。
难度=tk.StringVar(值=dif_enum[0])
def显示和设置难度()
全球当前困难
当前难度=难度。获取()
打印(1+dif_enum.index(demobility.get()),demobility.get())
对于dif_枚举中的dif:
Radiobutton(self,text=dif,value=dif,variable=demobility,command=show\u和\u set\u demobility).pack()
退出按钮=tk.button(self,text='quit',command=quit,font=MEDIUM\u font).pack(fill=X,side=BOTTOM)
类EquationPageBase(tk.Frame):
定义初始化(自身、父级、控制器、等效类型):
tk.Frame.\uuuu init\uuuuu(自,父)
标签(self,text=“数学问题测验”,font=LARGE\u font).pack(pady=10,padx=10)
标签(self,text=“数学方程程序”,font=MEDIUM\u font).pack(pady=10,padx=10)
#@etuc_comment:使用第三个参数'equal_type'显示当前方程类型。
tk.Label(self,text=“您已选择{}作为单位”。format(equal_type),font=SMALL_font)。pack(pady=10,padx=10)
tk.按钮(self,text=“重新选择单元”,font=MEDIUM\u font,command=lambda:controller.show\u frame(起始页)).pack(fill=X)
标签(self,text=”“).pack()
标签(self,text=”“).pack()
#-----这就是我希望方程式显示在下面标签中的位置-----#
self.submit\u计数器=0
self.correct_计数器=0
self.equation_strvar=tk.StringVar(值=“”)
from tkinter import *
from tkinter.ttk import *
class MainPanel(Frame):
def __init__(self, master):
Frame.__init__(self, master)
# first setup two StringVars. They will be linked to a Label and an Entry widget.
# we should keep a reference to these two StringVars, because we will call their method
# to read/write widget content.
self.msg2show = StringVar()
self.text_input = StringVar()
# this is a fixed Label widget whose display will no change.
# No need to keep a reference(meaning to assign it to a variable).
Label(self, text='If you click the button, the text in the entry widget will show above.').pack()
# this is a variable Label widget whose display is decided by the linked variable `self.msg2show`
Label(self, textvariable=self.msg2show).pack()
# this is a variable Entry widget whose content is saved into `self.text_input`
Entry(self, textvariable=self.text_input).pack()
# this is the button who will trigger `self.set_msg` on click.
Button(self, text='Set message', command=self.set_msg).pack()
def set_msg(self):
# get out what in the Entry widget through calling the `get()` method of `self.text_input`
text_in_entry_widget = self.text_input.get()
# and print it into console, for checking.
print(text_in_entry_widget)
# then we set that text into self.msg2show, and since it is linked with the variable Label widget
# the display of that Label will then be set to text_in_entry_widget.
self.msg2show.set(text_in_entry_widget)
# You can see here I print the `text_in_entry_widget` to console as well as to a Label.
# You can do it in the same way.
if __name__ == '__main__':
root = Tk()
MainPanel(root).pack()
root.mainloop()