繁体   English   中英

TkInter输入框被禁用

[英]TkInter Entry Box Being Disabled

我正在使用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

任何提示表示赞赏。

有两个明显的问题。

首先,您不应该使用

guess_button = Button(root, text="Guess", width=15, command=guessButton(guess_input,word,guesses))

因为您不能在命令config上调用带有参数的函数。

我的建议是在这里使用建议的方法之一,我特别喜欢使用functoolspartial方法的方法:

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:

暂无
暂无

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

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