1

我有一个单选按钮列表并链接到同一个变量,并且我有一个提交按钮,单击该按钮时我希望它将当前变量值传递给另一个函数,然后该函数将使用该数字。我使用了 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()
4

1 回答 1

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函数更改为打印变量的值,而不是打印变量本身。

于 2013-07-25T10:14:20.107 回答