我正在使用Tkinter开发GUI Python程序。
我有一个按下按钮时(以及加载程序时)调用的函数。该程序目前尚未完成,仅在当前点检查数据验证。由于默认条目是当前无效的,因此会引发错误。
然而,在此之后,输入框被禁用,不允许我输入任何数据。我无法弄清楚为什么会发生这种情况,我想知道是否有人可以告诉我原因,以便我可以解决问题。
由于
import sys
import random
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
root = Tk()
root.title("COSC110 - Guessing Game")
hint = StringVar()
guesses = []
guess_input = ''
def loadWordList(filename): #Load the words from a file into a list given a filename.
file = open(filename, 'r')
line = file.read().lower()
wordlist = line.split()
return wordlist
word = random.choice(loadWordList('words.txt'))
def getHint(word, guesses): #Get hint function, calculates and returns the current hint.
hint = ' '
for letter in word:
if letter not in guesses:
hint += '_ '
else:
hint += letter
return hint
def guessButton(guess, word, guesses):
guess = str(guess_input)
guess = guess.lower()
if not guess.isalpha():
is_valid = False
elif len(guess) !=1:
is_valid = False
else:
is_valid = True
while is_valid == False:
messagebox.showinfo("Error:","Invalid input. Please enter a letter from a-z.")
break
hint.set(getHint(word, guesses))
return hint
label_instruct = Label(root, text="Please enter your guess: ")
label_instruct.grid(row=1,column=1,padx=5,pady=10)
guess_input = Entry(root,textvariable=guess_input)
guess_input.grid(row=1, column=2)
guess_button = Button(root, text="Guess", width=15, command=guessButton(guess_input,word,guesses))
guess_button.grid(row=1, column=3,padx=15)
current_hint = Label(root, textvariable=hint)
current_hint.grid(column=2,row=2)
label_hint = Label(root, text="Current hint:")
label_hint.grid(column=1,row=2)
label_remaining = Label(root, text="Remaining guesses: ")
label_remaining.grid(column=1,row=3)
root.mainloop() # the window is now displayed
任何提示都表示赞赏。
答案 0 :(得分:0)
有两个明显的问题。
首先,你不应该使用
guess_button = Button(root, text="Guess", width=15, command=guessButton(guess_input,word,guesses))
因为你无法在命令config上调用带参数的函数。
我的建议是看看here并使用其中一种方法,我特别喜欢使用functools和partial
的方法:
from functools import partial
#(...)
button = Tk.Button(master=frame, text='press', command=partial(action, arg))
action
是您要调用的函数,arg
您要调用的参数用逗号分隔。
其次,您正在使用
guess = str(guess_input)
不会返回Entry类型的文本,而是使用
guess = guess_input.get()
PS:虽然与您的问题没有直接关系,但您应该使用
if var is False:
而不是
if var == False: