简体   繁体   English

Python Tkinter Radiobutton变量输出

[英]Python Tkinter Radiobutton variable output

I'm trying to find a way to take the value from a Radiobutton, set it to a variable, and use the variable outside the class in other parts of my code. 我试图找到一种方法从Radiobutton获取值,将其设置为变量,并在我的代码的其他部分使用类外的变量。 Heres a sample of my code: 下面是我的代码示例:

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)

Is there a way, preferably without use definitions and the command option, to set a variable "Method" to the value that the user selected? 有没有办法,最好没有使用定义和命令选项,将变量“Method”设置为用户选择的值? And then use that value outside the class. 然后在课堂外使用该值。

I tried using Method=self.v1.get() but that didn't work. 我尝试使用Method = self.v1.get()但这不起作用。

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()

Here is an example of what I mean in my comment. 这是我在评论中的意思的一个例子。 My example should print the value of whichever Radiobutton is currently selected when you close the window. 我的示例应该打印当您关闭窗口时当前选择的Radiobuttonvalue

In your case, depending on whichever value the Radiobutton has, you would decide which functions to call. 在您的情况下,根据Radiobutton具有的任何值,您将决定调用哪些函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM