我计划一个数学游戏。我希望计算标签1的randint +标签2的randint,然后检查我的输入是否与计算出的数字相同。
我想将z1加到z2并检查Entry是否相同,但是我不知道如何将一个随机数添加到另一个。
我无法将z1添加到z2,那该怎么做?这种情况应该在if...else
中发生吗?
从tkinter导入* 来自随机导入*
fenster = Tk()
fenster.title("Mathe-Spiel")
fenster.geometry("300x300")
def anfang():
z1 =label = Label(fenster, text=(randint(1,100)))
label.pack()
zp=label2 = Label(fenster, text="+")
label2.pack()
z2= label1 = Label(fenster, text=(randint(1,100)))
label1.pack()
a =label3 = Label(fenster,)
label3.pack()
e1=eingabe = Entry(fenster)
eingabe.pack()
e2=z1+z2
def ausgabe():
if (e1==e2):
a.configure(text=(eingabe.get()))
else:
a.configure(text="Falsch")
ergebnis = Button(fenster, text="ergebnis", command= ausgabe)
ergebnis.pack()
anfangsknopf = Button(fenster, text="Fange mit dem Spielen an", command=anfang)
anfangsknopf.pack()
mainloop()
答案 0 :(得分:1)
错误:您正在尝试将2个标签加在一起(e2 = z1 + z2),但是您希望将值添加到z1和z2文本选项中!
从z1和z2获取文本时,您可以获得正确的值,但是我会以不同的方式来做。
像这样:
from tkinter import Tk, IntVar, Button, Label, Entry
from random import randint
class Gui:
def __init__(self, master):
self.master = master
self.summand1 = IntVar()
self.summand2 = IntVar()
anfangsknopf = Button(self.master, text="Fange mit dem Spielen an", command=self.create_widgets)
anfangsknopf.pack()
def create_widgets(self):
""" create widgets on the fly """
try:
self.label1.destroy()
self.label2.destroy()
self.label3.destroy()
self.eingabe.destroy()
self.ergebnis.destroy()
self.answer.destroy()
except:
print("No widgets destroyed")
self.fill_summands()
self.label1 = Label(self.master, textvariable=self.summand1)
self.label2 = Label(self.master, text="+")
self.label3 = Label(self.master, textvariable=self.summand2)
self.eingabe = Entry(self.master)
self.ergebnis = Button(self.master, text="ergebnis", command= self.ausgabe)
self.answer = Label(self.master, text="...")
self.label1.pack()
self.label2.pack()
self.label3.pack()
self.eingabe.pack()
self.ergebnis.pack()
self.answer.pack()
self.eingabe.focus_set()
def get_random_nr(self):
""" get random number """
return randint(1,100)
def fill_summands(self):
""" set IntVar variables """
r_number1 = self.get_random_nr()
r_number2 = self.get_random_nr()
self.summand1.set(r_number1)
self.summand2.set(r_number2)
def ausgabe(self):
""" calculate addition """
try:
if self.summand1.get()+self.summand2.get() == int(self.eingabe.get()):
print("Correct")
self.answer.configure(text="Correct", fg="Green")
else:
print("Wrong")
self.answer.configure(text="Wrong", fg="Red")
except ValueError:
print("Please set a number in Entry widget")
self.answer.configure(text="Bitte gültige Nummer eingeben", fg="Red")
if __name__ == "__main__":
fenster = Tk()
fenster.title("Mathe-Spiel")
fenster.geometry("300x300")
app = Gui(fenster)
fenster.mainloop()