首页 > 解决方案 > 如何在 tkinter 单选按钮中获取/打印当前值

问题描述

我正在尝试在 oop 结构化应用程序中打印单选按钮的当前值。我已经看到了一些关于如何编写工作代码的解决方案(例如https://www.tutorialspoint.com/python/tk_radiobutton.htm),但是当我尝试在我的课程中使用它时,我做错了。

我有以下背景代码:

class OutFileGUI(tk.Tk): 

    def __init__(self, *args, **kwargs):

        tk.Tk.__init__(self, *args, **kwargs) 

        tk.Tk.wm_title(self, ".Out GUI") 

        container = tk.Frame(self)
        container.pack(side='top', fill='both', expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        menubar = tk.Menu(container)
        filemenu = tk.Menu(menubar, tearoff=0)
        filemenu.add_command(label="Read file", command=self.open_file)
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=quit)
        menubar.add_cascade(label="File", menu=filemenu)

        tk.Tk.config(self, menu=menubar)

        self.frames = {}

        for F in (StartPage, MainPage, ConvBehaviour, GaussPoints):
            frame = F(parent=container, controller=self) =
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(StartPage)

    def show_frame(self, page_name):

        frame = self.frames[page_name]
        frame.tkraise()

    def get_page(self, page_class):
        return self.frames[page_class]

    def open_file(self):
        name = askopenfilename(
                               filetypes=((".Out File", "*.out"), ("All Files", "*.*")),
                               title="Choose a file.")

        message = ("File location: " + str(name))
        print(message)

在下面的框架中,我试图放置一个单选按钮,并根据用户选择的值打印该值。

class ConvBehaviour(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="See behaviour", font=LARGE_FONT)
        label.pack(pady=10, padx=10)

        button1 = ttk.Button(self, text="Back to Home",
                             command=lambda: controller.show_frame(MainPage))
        button1.pack()

        button2 = ttk.Button(self, text="See points statistics",
                             command=lambda: controller.show_frame(GaussPoints))
        button2.pack()

        norms = [("norm 1", 1),
                 ("norm 2", 2),
                 ("norm 3", 3)]
                                                  #Here is the problem
        self.v1 = tk.IntVar()
        self.v1.set(1)

        for text, num in norms:
            radiobutton = tk.Radiobutton(self, text=text, value=num, variable=self.v1, command=self.show_choice)
            radiobutton.pack()


    def show_choice(self):
        print('int ' + str(self.v1.get()))

我遇到的问题是方法 show_choice(self) 在当前实现中不起作用。它根据用户选择打印 self.v1.set(1) 中设置的当前值,而不是 1、2、3 中的任何一个。问题出在哪里?

标签: python-3.xtkinterradio-button

解决方案


尝试构建一个尽可能小的示例,以便在尽可能多地消除背景噪音的同时,仍然会出现变量没有捕捉到用户输入的问题。另请参阅https://stackoverflow.com/help/mcve

例如,仅包含我可以从您的代码构建的单选按钮的最小示例如下(并且它按预期工作):

import tkinter as tk

def main():
    root = tk.Tk()

    norms = [("norm 1", 1),
             ("norm 2", 2),
             ("norm 3", 3)]

    v1 = tk.IntVar()
    v1.set(1)

    def show_choice():
        print('int ' + str(v1.get()))

    for text, num in norms:
        radiobutton = tk.Radiobutton(root, text=text, value=num, variable=v1, 
            command=show_choice)
        radiobutton.pack()

    root.mainloop()

if __name__ == '__main__':
    main()

尝试从那里开始构建 - 分小步进行(也许首先尝试添加您自己的继承自 tk.Frame 的类等)。这是必不可少的:不要从其他人那里复制大块代码(具有令人困惑的类和约定),而是从小的工作示例开始并向上工作。


推荐阅读