我有一个关于python GUI的特定项目的作业问题。
我的目标是创建一个GUI,它询问一个随机的数学方程式,如果方程式计算正确,那么我将收到一条消息,说明它是正确的。
我的主要问题是找出将我的语句放在哪里,以便它们显示在标签中;我有一个生成随机方程的文本框,下一个文本框是空白的,让我输入解决方案,然后在最后有一个" enter“按钮来评估我的解决方案。
它看起来是这样的:
[*randomly generated equation*][*Empty space to enter solution*] [ENTER]
我已经设法获得了布局和计算参数,但我不知道从哪里开始。
这是我到目前为止的代码:
class Equation(Frame):
def __init__(self,parent=None):
Frame.__init__(self, parent)
self.pack()
Equation.make_widgets(self)
Equation.new_problem(self)
def make_widgets(self):
Label(self).grid(row=0, column=1)
ent = Entry(self)
ent.grid(row=0, column=1)
Label(self).grid(row=0, column=2)
ent = Entry(self)
ent.grid(row=0, column=2)
Button(self, text='Enter', command=self.evaluate).grid(row=0, column=3)
def new_problem(self):
pass
def evaluate(self):
result = eval(self.get())
self.delete(0, END)
self.insert(END, result)
print('Correct')
发布于 2012-10-13 22:05:15
self.labeltext = StringVar() # in __init__
# ...
Label(self, textvariable=self.labeltext) # in make_widgets
# ...
self.labeltext.set("Correct!") # in evaluate
发布于 2012-10-13 22:06:04
在make_widgets()
中,您创建了一组小部件,但没有将它们赋给任何变量。这会阻止您在创建它们之后访问它们。尝试将它们赋给实例变量,例如:
def make_widgets(self):
self.equation_label = Label(self)
self.equation_label.grid(row=0, column=1) #notice that grid() is on another line
self.entry1 = Entry(self)
ent.grid(row=0, column=1)
self.solution_label = Label(self)
self.solution_label.grid(row=0, column=2)
self.entry2 = Entry(self)
ent.grid(row=0, column=2)
self.button = Button(self, text='Enter', command=self.evaluate)
self.button.grid(row=0, column=3)
这样,您就可以从类中的其他函数访问它们,如下所示:
self.solution_label.config(text="Hello World")
所以你的回调看起来更像这样:
def evaluate(self):
result = eval(self.get())
self.solution_label.config(text=str(result))
对于Entry
小部件,您可以使用J.F.Sebastian的答案,也可以使用insert
和delete
方法(看起来您一直在尝试这样做):
def evaluate(self):
#...some code...
self.solution_entry.delete(0, END)
self.solution_entry.insert(0, "Some text")
#...more code...
Tkinterbook是一个很好的资源,可以用来查找小部件配置选项等。
编辑
有关设置小部件值的另一种方法,请参阅J.F.Sebastian's answer。
https://stackoverflow.com/questions/12877212
复制相似问题