[英]command in button not called tkinter
我有一個代碼可從文本框中獲取輸入,然后將輸入寫入文本文件:請幫助我糾正以下錯誤和代碼
我的代碼:
import tkinter as tki
class App(object):
def __init__(self,root):
self.root = root
# create a Frame for the Text and Scrollbar
txt_frm = tki.Frame(self.root, width=600, height=400)
txt_frm.pack(fill="both", expand=True)
# ensure a consistent GUI size
txt_frm.grid_propagate(False)
self.txt1 = tki.Text(txt_frm, borderwidth=3, relief="sunken", height=4,width=55)
self.txt1.config(font=("consolas", 12), undo=True, wrap='word')
self.txt1.grid(row=0, column=1, sticky="nsew", padx=2, pady=2)
button = tki.Button(self,text="Click", command = self.retrieve_input)
button.grid(column=2,row=0)
def retrieve_input(self):
input = self.txt1.get("0.0",'END-1c')
with open('text.txt','w') as f:
f.write(input)
f.close()
root = tki.Tk()
app = App(root)
root.mainloop()
錯誤:
File "C:/Python34/testtext.py", line 21, in <module>
app = App(root)
File "C:/Python34/testtext.py", line 13, in __init__
button = tki.Button(self,text="Click", command = self.retrieve_input)
File "C:\Python34\lib\tkinter\__init__.py", line 2156, in __init__
Widget.__init__(self, master, 'button', cnf, kw)
File "C:\Python34\lib\tkinter\__init__.py", line 2079, in __init__
BaseWidget._setup(self, master, cnf)
File "C:\Python34\lib\tkinter\__init__.py", line 2057, in _setup
self.tk = master.tk
AttributeError: 'App' object has no attribute 'tk'
您將按鈕小部件的父項作為self,這是一個非tk對象。
button = tki.Button(self...
如果您試圖將self.root設置為父級,那么它也將無法工作,因為您已經將“ txt_frm”打包到了它上。 (並且您不能在同一父級下混合打包和網格化。
您所要做的就是將父級更改為txt_frm
button = tki.Button(txt_frm,text="Click", command = self.retrieve_input)
button.grid(column=2,row=0)
我也建議將tkinter導入為tk,這是更標准的做法。
看一下回溯錯誤,如果代碼是非常線性和簡單的,那么這應該是您所需要的。
如果要將類實例self用作實例,則必須在tkinter類下初始化該類,self之下現在是tkinter框架。
class App(tk.Frame):
def __init__(self, root):
tk.Frame.__init__(self, root)
def makeButton(self):
widget = tk.Button(self)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.