簡體   English   中英

無法在 Python 3 中獲取 tkinter Entry 小部件的內容

[英]Can't get contents of tkinter Entry widget in Python 3

我開始使用 Python 3,但在從 tkinter 小部件獲取值時遇到問題。 當我運行我的代碼時,我收到“名稱 edtGetMe 未定義”錯誤。 誰能看到我哪里出錯了?

from tkinter import *

# Define the class that forms my window.  
class Window(Frame):

def __init__(self, master=None):
    Frame.__init__(self, master)
    self.master = master
    self.init_window()

# Init the class.
def init_window(self):
    # Place widgets on the window.
    self.pack(fill=BOTH, expand=1)

    # Quit button.
    btnCancel = Button (self, text="Cancel", command=self.cancel_out)
    btnCancel.place (x=10, y=120)

    # Action button.
    btnAction = Button (self, text="Set Text", command=self.action)
    btnAction.place (x=100, y=120)

    # The Editboxes.
    edtGetMe = Entry (self)
    edtSetMe = Entry (self)
    edtGetMe.place (y=10, x=10, width=380, height=100)
    edtSetMe.place (y=155, x=10, width=380, height=100)

def cancel_out(self):
    exit()

def action (self):
    # Get the entry from the GetMe box.
    self.usrText = edtGetMe.get()
    # Stuff it into the other box.
    edtSetMe.insert(self.usrText)

def main():
     root = Tk()

# Size of window.
root.geometry("400x300")

# Start Window Class. 
app = Window(root)
root.mainloop()

if name == " main ": main()

首先,我將edtGetMe替換為edtGetMeself.edtGetMe也是edtSetMe ,因此可以從所有類函數訪問這些變量。 然后我在你的行self.edtSetMe.insert("insert", self.usrText)添加了“插入”。 你也有縮進問題。

嘗試這個 :

from tkinter import *

# Define the class that forms my window.  
class Window(Frame):

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.master = master
        self.init_window()

    # Init the class.
    def init_window(self):
        # Place widgets on the window.
        self.pack(fill=BOTH, expand=1)

        # Quit button.
        btnCancel = Button (self, text="Cancel", command=self.cancel_out)
        btnCancel.place (x=10, y=120)

        # Action button.
        btnAction = Button (self, text="Set Text", command=self.action)
        btnAction.place (x=100, y=120)

        # The Editboxes.
        self.edtGetMe = Entry (self)
        self.edtSetMe = Entry (self)
        self.edtGetMe.place (y=10, x=10, width=380, height=100)
        self.edtSetMe.place (y=155, x=10, width=380, height=100)

    def cancel_out(self):
        exit()

    def action (self):
        # Get the entry from the GetMe box.
        self.usrText = self.edtGetMe.get()
        # Stuff it into the other box.
        self.edtSetMe.insert("insert", self.usrText)

def main():
    root = Tk()

    # Size of window.
    root.geometry("400x300")

    # Start Window Class. 
    app = Window(root)
    root.mainloop()

if __name__ == '__main__':
    main()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM