[英]Tkinter NameError
我正在嘗試制作一個簡單的程序,它可以 select 程序並啟動它們,但是當我 select 列表中的一個 porgram 時,它給出了一個名稱錯誤
from tkinter import *
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self,master)
self.pack(fill=BOTH, expand=1)
var=IntVar
example=Checkbutton(self, text="example", variable=var, onvalue=1, offvalue=0, command=self.example)
example.place(x=0,y=0)
def example(self):
if (example.get() == 1):
print("1")
elif (example.get() == 0):
print("0")
root=Tk()
app=Window(root)
root.geometry("220x120")
root.resizable(width=False, height=False)
root.mainloop()
當我運行它時,它工作正常,但是在單擊復選框時它會給出錯誤
NameError:名稱“示例”未定義
我嘗試使用不同的關鍵字進行搜索,但沒有找到解決方案。 我取得的唯一進展是從def example
后面刪除(self)
,然后出現以下錯誤
TypeError: example() 采用 0 位置 arguments 但給出了 1
任何幫助將不勝感激
您的代碼存在許多問題:
example
在方法中可見,您要么必須全局聲明它,要么必須執行self.example
。get()
,您需要使用IntVar
var
,而不是 Checkbox 本身。var
必須是self.var
才能可見。var
需要是IntVar
的一個實例,所以你需要括號: var = IntVar()
總而言之,應用這些更改后,它將是:
from tkinter import *
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self,master)
self.pack(fill=BOTH, expand=1)
self.var=IntVar()
example=Checkbutton(self, text="example", variable=self.var, onvalue=1, offvalue=0, command=self.example)
example.place(x=0,y=0)
def example(self):
if (self.var.get() == 1):
print("1")
elif (self.var.get() == 0):
print("0")
root=Tk()
app=Window(root)
root.geometry("220x120")
root.resizable(width=False, height=False)
root.mainloop()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.