问题描述
我不小心创建了一个无限循环 :D
当用户操作 tkinter Scale
时,我想使用下面的函数调用警告(如果文件不存在)。此消息应仅显示一次。但是当用户点击(在中间)tkinter Scale
按钮时,Scale
按钮被拖到最后并且消息被一次又一次地调用。
我怎样才能防止这种情况发生?
def change_max_y(v):
try:
# Some functions to check if the file exists
# Open some json file
# Do some calculation
except FileNotFoundError:
# Some function to open the messageBox:
comment = tk.messageBox.askyesno('Title',"Something is missing.",icon='warning')
if comment:
# Do something
else:
return
ttk.Scale(settingsWin,orient=tk.HORIZONTAL,from_=0,to=4,length=110,command=change_max_y). \
place(x=210,y=90)
解决方法
您可以定义一个初始值为 0 的全局变量(我知道这是不好的做法,但有时必须这样做)。在您的回调函数中,您查看该变量是否为 0,如果是,则显示您的消息框并将其设置为 1。如果不是,您什么都不做。您提供的代码进行了相应修改:
already_shown = 0
def change_max_y(v):
try:
# Some functions to check if the file exists
# Open some json file
# Do some calculation
except FileNotFoundError:
# Some function to open the messagebox:
if not already_shown:
comment = tk.messagebox.askyesno('Title',"Something is missing.",icon='warning')
already_shown = 1
if comment:
# Do something
else:
return # note : you can delete this else statement,as the function
# will return None by itself when there is nothing more to be
# done
ttk.Scale(settingsWin,orient=tk.HORIZONTAL,from_=0,to=4,length=110,command=change_max_y). \
place(x=210,y=90)