繁体   English   中英

Python GUI生成数学方程式

[英]Python GUI generate math equation

我有一个带有python GUI的特定项目的作业问题。

我的目标是创建一个GUI,询问随机数学方程式,如果方程式被正确评估,那么我将收到一条消息,说明它是正确的。

我的主要问题是找出放置我的陈述的位置,以便它们出现在标签中; 我有1个文本框生成随机方程式,下一个文本框是空白的,我输入解决方案,然后在结尾处的“回车”按钮来评估我的解决方案。

它看起来像这样:

[*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')
self.labeltext = StringVar() # in __init__

# ...
Label(self, textvariable=self.labeltext) # in make_widgets

# ...
self.labeltext.set("Correct!") # in evaluate

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小部件,您可以使用JFSebastian的答案,也可以使用insertdelete方法(无论如何,它似乎都是您尝试做的):

def evaluate(self):
    #...some code...
    self.solution_entry.delete(0, END)
    self.solution_entry.insert(0, "Some text")
    #...more code...

Tkinterbook是查找窗口小部件配置选项等的绝佳资源。

编辑

有关设置窗口小部件值的另一种方法,请参阅JFSebastian的答案

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM