按钮中的命令不称为tkin

2024-09-27 20:18:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个代码从文本框中获取输入,然后将输入写入文本文件: 请帮助我纠正我的错误和我的代码从以下

我的代码:

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' 

Tags: inpyselftxtappinputinittkinter
1条回答
网友
1楼 · 发布于 2024-09-27 20:18:01

您的按钮小部件的父对象是self,这是一个非tk对象。你知道吗

button = tki.Button(self...

如果你想自根家长,它也不会工作,因为你已经把你的“txt\u frm”到它。(并且不能在同一个父项下混合打包和网格。你知道吗

你所要做的就是把父对象改成txt\u 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)

相关问题 更多 >

    热门问题