I am trying to get the value from radiobutton in tkinter but getting eror as "NameError: name 'var' is not defined". Below is my entire code. with

I am trying to get the value from radiobutton in tkinter but getting eror as "NameError: name 'var' is not defined". Below is my entire code. with

我 运行 遇到了变量问题。无法理解错误。我的 objective 是使用以下代码从 Radiobutton 获取值。

import tkinter as tk


class App:
    def __init__(self, root):
        root.title("undefined")
        width=600
        height=500
        screenwidth = root.winfo_screenwidth()
        screenheight = root.winfo_screenheight()
        alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
        root.geometry(alignstr)
        root.resizable(width=False, height=False)
        
        R1 = tk.Radiobutton(root, text="Option 1", variable=var, value='10',
                  command=sel)
        R1.place(x=100,y=70,width=85,height=25)
        R2 = Radiobutton(root, text="Option 2", variable=var, value='12',
                  command=sel)
        R2.place(x=200,y=70,width=85,height=25)
        
        def sel():
            selection = "You selected  " + str(var.get())
            print(selection)


if __name__ == "__main__":
    root = tk.Tk()
    app = App(root)
    root.mainloop()

您尚未在任何地方定义变量 var,因此无法将其传递给 Radiobutton。您需要先声明您的变量,然后才能使用它。