带有 tkinter 消息框和缩放按钮的无限循环(Python | Tkinter)
Infinite loop with tkinter messagebox and scale button (Python | Tkinter)
我不小心创建了一个无限循环: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)
我不小心创建了一个无限循环: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)