我确定已经问过这个问题,我遇到了一些解决方案,但它们对我不起作用。如果用户给出的输入错误,我试图禁用我的tkinter gui中的按钮。
有两个输入字段,以秒为单位输入时间(分别为t1和t2)。完成输入后,用户单击“确认”按钮。我现在想做的是,如果没有正确输入时间,例如t1> t2,这将引发错误,并且代码将进入函数-time_error()
一旦出现此错误,我想禁用'Go'按钮,以使脚本无法执行。
我正在尝试在time_error()函数中禁用此“转到”按钮,但无法执行此操作。
以下是我的代码:
import tkinter as tk
from tkinter import ttk
import pdb
root = tk.Tk()
color = '#aeb3b0'
IntroCanvas = tk.Canvas(height = 200, width = 400, bg = color)
IntroCanvas.pack()
# time error funtion ********** THIS IS NOT WORKING FOR ME **************
def time_error():
GoButton = tk.Button(root, text="GO!", command=go,bg = 'green', fg = 'white', width=4)
GoButton.place(relx=0.4, rely=0.5)
GoButton = tk.Button.configure(root,state = 'DISABLED')
# ****************************************************************************
# t1_init ************ ENTER FIRST TIME VALUE IN SECONDS ****
def blank_t1entry(event):
t1entry.delete(0, "end")
return None
t1entry = tk.Entry(width = 13)
t1entry.place(relx = 0.1, rely = 0.25)
t1entry.insert(0,"From seconds")
t1entry.bind("<Button-1>", blank_t1entry)
# t2_init ************ ENTER SECOND TIME VALUE IN SECONDS ****
def blank_t2entry(event):
t2entry.delete(0, "end")
return None
t2entry = tk.Entry(width = 12)
t2entry.place(relx = 0.4, rely = 0.25)
t2entry.insert(0,"To seconds")
t2entry.bind("<Button-1>", blank_t2entry)
# ****** GET THE ENTERED TIME VALUES AND COMPARE THEM TO SEE IF THEY ARE APPROPRIATE, ELSE THROW ERROR ***
def confirmTime_comp():
global t1_comp_init, t2_comp_init
if not ((str.isnumeric(str(t1entry.get()).replace('.','')))|(t1entry.get()=='From seconds')):
time_error()
else:
t1_comp_init = t1entry.get()
if not ((str.isnumeric(str(t2entry.get()).replace('.','')))|(t2entry.get()=='To seconds')):
time_error()
else:
t2_comp_init = t2entry.get()
# below lines are for throwing an error if t1 > t2 or t1 < 0
pdb.set_trace()
if not ('seconds' in t1_comp_init):
if not ('seconds' in t2_comp_init):
if float(t1_comp_init) >= float(t2_comp_init):
time_error()
elif float(t1_comp_init) < 0:
time_error()
# ****** BUTTON TO CONFIRM TIME ENTRIES *******************
CompTimeButton = tk.Button(root, text="Confirm", command=confirmTime_comp,bg = 'green', fg = 'white')
CompTimeButton.place(relx=0.6, rely=0.25)
def go():
printLabel = tk.Label(root, text = 'Go Button Pressed')
printLabel.place(relx = 0.35, rely = 0.75)
GoButton = tk.Button(root, text="GO!", command=go,bg = 'green', fg = 'white', width=4)
GoButton.place(relx=0.4, rely=0.5)
root.mainloop()
此外,如果用户输入不正确,还有其他更优雅的方法可以阻止运行脚本吗?
谢谢
R
我想我找到了一种禁用按钮的方法。它所需要的只是:
def time_error():
GoButton['state'] = tk.DISABLED