【问题标题】:Having Troubles with Python GUI(Tkinter)Python GUI(Tkinter)遇到问题
【发布时间】:2018-06-14 13:40:36
【问题描述】:

大家好,需要一些有关 Python GUI (Tkinter) 的帮助。我遇到的问题是我试图让每个单选按钮产生不同的消息框,我试图解决它的方式不起作用并且想知道为什么它不起作用。 (下面是我正在使用的代码)

from tkinter.messagebox import *
from tkinter import *


def button_press():
    if button1:
        showinfo(title="Message", message="You selected to enter a new item.")
    elif button2:
        showinfo(title="Message", message="You selected to remove an item by its element number.")
root_window = Tk()
option_value = IntVar()

button1 = Radiobutton(root_window, text="Enter a new item.", variable=option_value, value=1, command=button_press)
button1.pack(anchor=W)

button2 = Radiobutton(root_window, text="Remove an item by its element number.", variable=option_value, value=2,command=button_press)
button2.pack(anchor=W)

root_window.mainloop()

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    您应该获取变量 option_value 的值,以便知道单击了哪个单选按钮。这可以使用 option_value.get() 来完成。

    from tkinter.messagebox import *
    from tkinter import *
    
    
    def button_press():
        if option_value.get() == 1:
            showinfo(title="Message", message="You selected to enter a new item.")
        elif option_value.get() == 2:
            showinfo(title="Message", message="You selected to remove an item by its element number.")
    root_window = Tk()
    option_value = IntVar()
    
    button1 = Radiobutton(root_window, text="Enter a new item.", variable=option_value, value=1, command=button_press)
    button1.pack(anchor=W)
    
    button2 = Radiobutton(root_window, text="Remove an item by its element number.", variable=option_value, value=2,command=button_press)
    button2.pack(anchor=W)
    
    root_window.mainloop()
    

    【讨论】:

    • @Origin27 请接受答案,让其他人知道问题已解决。
    【解决方案2】:

    您可以使用一组选项来避免级联 if 语句,并在循环中创建单选按钮:

    import tkinter as tk
    from tkinter import messagebox
    
    
    def button_press(option):
        messagebox.showinfo(title="Message", message=f"You selected to {messages[option]}")
    
    
    if __name__ == '__main__':
    
        root_window = tk.Tk()
        option_value = tk.IntVar()
        messages = ["enter a new item.",
                    "remove an item by its element number."]
        for idx, msg in enumerate(messages):
            tk.Radiobutton(root_window,
                           text=msg,
                           variable=option_value,
                           value=idx+1,
                           command=lambda option=idx: button_press(option)).pack(anchor=tk.W)
    
        root_window.mainloop()
    

    最好不要用* imports 混淆命名空间

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-19
      • 1970-01-01
      • 2018-02-19
      • 1970-01-01
      • 2014-04-21
      • 1970-01-01
      相关资源
      最近更新 更多