尝试在tkinter中传递当前的radiobutton值,但未定义全局名称

时间:2013-07-25 08:23:27

标签: python user-interface python-3.x tkinter

我有一个radiobuttons列表并链接到同一个变量,我有一个提交按钮,当点击时,我希望它将当前变量值传递给另一个函数,然后使用该数字。我使用lambda函数但是当应该调用函数时,我得到全局名称'num'没有定义。 num是我的功能。以下是我的代码。非常感谢你。

from tkinter import *
import random

class App:

def __init__(self, master):


def say_one(self):

    v = IntVar()
    window = Toplevel(root)

    for i in range(1,11):
        self.label = Radiobutton(
            window, text = i , fg = "red", 
            value = i, variable = v
        ).grid(row =i, column =0)

    # error is occurring in the next line
    self.report = Button(
        window, text="submit", command= lambda : num (v) 
    ).grid(row = 12, column = 0)        

def num( number):
    print(number)

root = Tk()

app = App(root)

root.mainloop()

1 个答案:

答案 0 :(得分:3)

正确缩进代码。

from tkinter import *
import random

class App:
    def __init__(self, master):
        self.say_one()

    def say_one(self):
        v = IntVar()
        window = Toplevel(root)

        for i in range(1,11):
            self.label = Radiobutton(
                window, text = i , fg = "red", 
                value = i, variable = v
            ).grid(row =i, column =0)

        # error is occurring in the next line
        self.report = Button(
            window, text="submit", command=lambda: num(v) 
        ).grid(row = 12, column = 0)        

def num(var):
    print(var.get())

root = Tk()
app = App(root)
root.mainloop()

我修改了缩进,将num函数更改为打印变量的值而不是打印变量本身。