(Python 3.4.1)
嘿,我有这个简单的小猜测我在Tkinter的数字游戏,但由于某种原因它没有工作......谁能明白为什么?from tkinter import *
from random import random
import tkinter.messagebox
window = Tk()
def Guess():
if int(guessnum) == int(Number):
print("Well Done!")
exit()
elif int(guessnum) >= int(Number):
print("Too big")
elif int(guessnum) <= int(Number):
print("Too small")
Number = (round(random() * 10))
window.title("Guess My Number")
window["padx"] = 70
window["pady"] = 20
guessnum="1"
entryWidget=Entry(window,textvariable=guessnum).grid(row=1,column=0)
button = Button(window, text="Guess",command=Guess()).grid(row=2,column=0)
window.mainloop()
答案 0 :(得分:1)
您在一行中犯了两个经典Tkinter
错误:
button = Button(window, text="Guess", command=Guess()).grid(row=2,column=0)
# ^ assigned result of call to command, not
# the actual function
# ^ assigned result of grid
# (None) to button rather
# than the Button
这一行等同于:
Guess()
_ = Button(..., command=None)
button = _.grid(...)
你应该做的:
button = Button(window, text="Guess", command=Guess)
button.grid(row=2,column=0)
注意从Guess
和grid
调用中移除的括号拆分为单独的行
答案 1 :(得分:0)
testvariable选项必须是StringVar类的实例。
guessnum = StringVar
guessnum.set("1") # optional, otherwise '' I believe
我推荐这个tkinter reference并在编写tkinter小部件时不断使用它我并不完全熟悉,甚至有时在这里回答问题。