【问题标题】:Python Tkinter Radiobutton variable outputPython Tkinter 单选按钮变量输出
【发布时间】:2015-09-11 00:07:56
【问题描述】:

我正在尝试找到一种方法来从 Radiobutton 中获取值,将其设置为变量,然后在代码的其他部分中使用类外部的变量。这是我的代码示例:

from Tkinter import *

class Window():

    def __init__(self, master):

        self.master = master
        self.v1 = IntVar()

        Label(master, text="""Which Method?""",justify = LEFT, padx = 20).pack()
        Radiobutton(master, text="Positive",padx = 20, variable=self.v1, value=1).pack(anchor=W)
        Radiobutton(master, text="Negative", padx = 20, variable=self.v1, value=2).pack(anchor=W)
        Radiobutton(master, text="Both", padx = 20, variable=self.v1, value=3).pack(anchor=W)

有没有办法,最好不使用定义和命令选项,将变量“方法”设置为用户选择的值?然后在类外使用该值。

我尝试使用 Method=self.v1.get() 但没有奏效。

【问题讨论】:

  • 你不能在课堂外使用w.v1.get() 访问它吗? (假设wWindow实例的名称)
  • “那行不通”是什么意思?发生了什么?这正是您从IntVar 获取值的方式。

标签: python variables tkinter radio-button


【解决方案1】:
from Tkinter import *

class Window():

    def __init__(self, master):

        self.master = master
        self.v1 = IntVar()

        Label(master, text="""Which Method?""",justify = LEFT, padx = 20).pack()
        Radiobutton(master, text="Positive",padx = 20, variable=self.v1, value=1).pack(anchor=W)
        Radiobutton(master, text="Negative", padx = 20, variable=self.v1, value=2).pack(anchor=W)
        Radiobutton(master, text="Both", padx = 20, variable=self.v1, value=3).pack(anchor=W)

root = Tk()
w = Window(root)
w.master.mainloop()

print "The radiobutton outside of the class: %d" %w.v1.get()

这是我在评论中的意思的一个例子。我的示例应该在您关闭窗口时打印当前选择的Radiobutton 中的value

在您的情况下,根据Radiobutton 的值,您将决定调用哪些函数。

【讨论】:

    猜你喜欢
    • 2015-06-15
    • 2016-09-01
    • 2016-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-16
    • 2016-09-01
    相关资源
    最近更新 更多