tkinter如何知道组合框是否改变了值

2024-10-02 22:27:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python 3.9.0,目前正在为一个简单的游戏创建一个设置窗口。 在设置中,您可以选择难度,我想选择 “自定义”难度,这仅仅意味着手动选择游戏的X轴和Y轴

from tkinter import *
import tkinter.font as font
import tkinter.ttk as ttk
import tkinter as tk

settingsWin = tk.Tk()
settingsWin.title('Start Menu')
settingsWin.geometry("500x500")
settingsWin.resizable(0, 0)

back = tk.Frame(master=settingsWin,bg='white')
back.pack_propagate(0)
back.pack(fill=tk.BOTH, expand=1)

# General Font for general use
GeneralFont = font.Font(family='Helvetica', size=15)

# Label and Combobox for game Difficulty
difficulty_label = tk.Label(master=back, text='Game Difficulty:', font=GeneralFont, bg='white')
difficulty_label.place(x=60, y=120)
DIFFICULTY_OPTIONS = [
"Easy",
"Hard",
"Harder",
"Hardest",
"Custom"
]
difficulty_combobox = ttk.Combobox(master=back, state="readonly", values=DIFFICULTY_OPTIONS,font=GeneralFont, width=8)
difficulty_combobox.current(0)
difficulty_combobox.place(x=220, y=120)

# custom Difficulty in X and Y entries
def callback(input):
    if input.isdigit():
        if len(input) > 3:
            print(input)
            return False
        else:
            print(input) 
            return True
    elif input is "": 
        print(input) 
        return True
    else: 
        print(input) 
        return False
reg = settingsWin.register(callback)
X_label = tk.Label(master=back, text='X:', font=GeneralFont, bg='white')
X_label.place(x=60, y=185)
X_entry = tk.Entry(master=back, font=GeneralFont, bg='white', width=8)
X_entry.place(x=90, y=185)
X_entry.config(validate="key", validatecommand=(reg, '%P'))
Y_label = tk.Label(master=back, text='Y:', font=GeneralFont, bg='white')
Y_label.place(x=200, y=185)
Y_entry = tk.Entry(master=back, font=GeneralFont, bg='white', width=8)
Y_entry.place(x=230, y=185)
Y_entry.config(validate="key", validatecommand=(reg, '%P'))

只有当您在困难中选择“自定义”时,我才想要X_entryY_entry拥有state="normal"。所以我写了这个:

if difficulty_combobox.get() != 4:
    X_entry.config(state="disabled")
    Y_entry.config(state="disabled")
else:
    X_entry.config(state="normal")
    Y_entry.config(state="normal")

但是它不起作用,我猜我需要在difficulty_combobox当前值更改时执行这个If/Else语句?如果是,我该怎么做

提前谢谢


Tags: masterconfiginputbackplacelabeltkbg