簡體   English   中英

Python GUI tkinter NameError

[英]Python GUI tkinter NameError

我在這里是新手,我在使用Python Tkinter進行測驗時遇到問題。

所以這是代碼:

b5 = Button(root, text="Next Question",command=question_2_output)
b5.configure(command = des)
b5.pack(side=BOTTOM)

用這個按鈕,即時通訊試圖訪問兩個功能。 - >

def question_2_output():

    lab7 = Label(root, text="Qestion 2 Qestion 2 Qestion 2 Qestion 2", 
    font="Verdana 11 italic")
    lab7.pack()
    lab7.place(x = 350, y = 60)


def des():
    q1.destroy()

使用此代碼,我嘗試將lab7放在先前問題q1所在的位置,並銷毀/刪除舊標簽(問題)。 但是我收到此錯誤NameError:未定義名稱'q1'。 我無法銷毀q1。 q1在此功能中。

def question_1_output():
    q1 = Label(root, text="This is a very very very very very long question?", font="Verdana 11 italic")
    q1.pack()
    q1.place(x = 350, y = 60)

有幫助嗎? 謝謝!

我認為您最好更新標簽而不是銷毀標簽並添加新標簽。

我還將使用一個類來構建此GUI,因為使用類屬性更容易閱讀。 避免使用global是一個好習慣,我們可以使用類屬性來做到這一點。

這是一個有關如何更新標簽和按鈕的簡單示例。

import tkinter as tk


class GUI(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent=parent
        self.question_label = tk.Label(self, text="Question 1", font="Verdana 11 italic")
        self.question_label.pack()
        self.b1 = tk.Button(self, text="Next Question",command=self.question_2_output)
        self.b1.pack(side=tk.BOTTOM)

    def question_1_output(self):
        self.question_label.config(text="Question 1")
        self.b1.configure(text="Next Question", command=self.question_2_output)

    def question_2_output(self):
        self.question_label.config(text="Question 2")
        self.b1.configure(text="Previous Question", command=self.question_1_output)


if __name__ == "__main__":
    root = tk.Tk() 
    GUI(root).pack()
    tk.mainloop()

在您的question_1_output()函數和des()函數中將其聲明為global variable q1

def des():
    global q1
    q1.destroy()


def question_1_output():
    global q1
    q1 = Label(root, text="This is a very very very very very long question?", font="Verdana 11 italic")
    q1.pack()

並讓你button執行兩個功能,你可以這樣來做

b5 = Button(root, text="Next Question", command=lambda:[des(), question_2_output()])
b5.pack(side=BOTTOM)

q1在功能question_1_output的本地范圍內,因此在功能des不可見。

重新排序定義或從函數返回對象,如下所示:

def question_1_output():
    q1 = Label(root, text="This is a very very very very very long question?", font="Verdana 11 italic")
    q1.pack()
    q1.place(x = 350, y = 60)
    return q1

def des(question):
    question.destroy()

q1 = question_1_output()
des(q1)

盡管我不明白函數des如果它只是在對象上調用destroy的話。

暫無
暫無

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

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