2 回答

TA貢獻1725條經(jīng)驗 獲得超8個贊
問題是因為當(dāng)代碼運行時,它直接調(diào)用numRamdom(),也就是說,最初條目小部件是空的,并且它們使用這些空條目小部件運行它,因此出現(xiàn)錯誤。因此,只需分配一個按鈕和一個命令,例如:
b = tkinter.Button(root,text='Click me',command=numRamdom)
b.grid(row=1,column=0)
mainloop()請務(wù)必在之前、之后說這句話def numRamdom():。僅當(dāng)單擊按鈕時該按鈕才運行該功能。
或者,如果您想要無按鈕,請嘗試:
方法一:
root.after(5000,numRamdom) #after 5 sec it will execute function
但請記住,如果用戶在 5 秒內(nèi)沒有正確輸入,則會彈出一些錯誤。
方法2:
def numRamdom(event):
......
entryWriteNumber.bind('<Return>',numRamdom)
這樣,如果您在輸入小部件中按 Enter 鍵(輸入數(shù)據(jù)后),它將運行該功能。
希望這有幫助,如果有任何錯誤請告訴我。

TA貢獻1795條經(jīng)驗 獲得超7個贊
這是一個基于您的代碼的完整工作示例。您的問題是嘗試在其中包含任何內(nèi)容之前轉(zhuǎn)換條目的內(nèi)容。要解決此問題,您可以添加一個調(diào)用命令的按鈕numRamdom()
import tkinter
import random
window = tkinter.Tk()
window.geometry('600x500')
x = random.randint(1,300)
remainingTime = True
Attempts = 4
def numRamdom():
global Attempts, lblClue, x
if Attempts > 0:
numWritten = int(entryWriteNumber.get())
if numWritten < x:
lblClue.configure(text = 'Its a bigger number')
Attempts = Attempts -1
elif numWritten > x:
lblClue.configure(text = 'Its a smaller number')
Attempts = Attempts -1
else:
lblClue.configure(text = 'Congratulations ;)')
remainingTime = False
#return remainingTime, countdown(0)
if Attempts == 0:
remainingTime = False
#return remainingTime, countdown(0), Attempts, gameOver()
else:
lblClue.configure(text = "You ran out of attempts!")
entryWriteNumber = tkinter.Entry(window)
entryWriteNumber.grid(column = 0, row = 1, padx = 10, pady = 10)
entryWriteButton = tkinter.Button(window, text = "Push me!", command = numRamdom)
entryWriteButton.grid(column = 1, row = 1)
lblClue = tkinter.Label(window)
lblClue.grid(row = 2, column = 1)
window.mainloop()
如果傳遞的值無法轉(zhuǎn)換為整數(shù),您仍然會收到錯誤,但這很容易通過語句修復(fù)if。
添加回答
舉報