使用Python GUI(Tkinter)遇到麻烦

时间:2018-06-14 05:02:47

标签: python tkinter

嘿伙计们需要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()

2 个答案:

答案 0 :(得分:3)

您应该获取变量 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()

答案 1 :(得分: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

来混淆命名空间