在另一個專案中,我有一堆標簽,只要給出字串串列就會更新。但是如果我想在這個串列中添加一個字串并用標簽顯示它,我將不得不再次銷毀并重新制作它們。為了簡化它,下面的代碼是我的起點。
from tkinter import *
root = Tk()
a = Label(root, text ="Hello World")
a.pack()
b = Label(root, text = "Goodbye World")
b.pack()
# third label to add between label A and B
root.mainloop()
是否有某種插入功能或其他方法來解決這個問題?
編輯:布萊恩·奧克利的回答:
應在標簽包中使用 before/after 引數
# third label to add between label A and B
c = Label(root, text="Live long and prosper")
c.pack(before=b)
uj5u.com熱心網友回復:
您呼叫的順序pack很重要,因為它確定了小部件相對于彼此出現的順序。pack還提供了更改該順序的引數。您可以指定before在另一個小部件之前添加一個小部件,并將小部件after放置在之后。
此代碼將第三個標簽放在小部件之前b:
# third label to add between label A and B
c = Label(root, text="Live long and prosper")
c.pack(before=b)
此代碼將第三個標簽放在小部件之后a:
# third label to add between label A and B
c = Label(root, text="Live long and prosper")
c.pack(after=a)

uj5u.com熱心網友回復:
我不完全確定這就是您的問題的意思,但是如果您想在 Label1 和 Label2 (a, b) 之間插入第三個標簽,只需手動插入即可。
from tkinter import *
root = Tk()
a = Label(root, text="Hello World")
a.pack()
# third label to add between label A and B
c = Label(root, text="Middle Label")
c.pack()
b = Label(root, text="Goodbye World")
b.pack()
root.mainloop()
這樣它就會在螢屏上顯示在 a 和 b 之間。如果您想將新文本插入到已經存在的標簽中,您可以使用 .configure() 方法隨時更改特定標簽的文本,如下所示:
from tkinter import *
lst = ["Oof"]
root = Tk()
a = Label(root, text="Hello World")
a.pack()
# third label to add between label A and B
c = Label(root, text="Middle Label")
c.pack()
b = Label(root, text="Goodbye World")
b.pack()
# Here I will add a simple code that asks the user to enter a number
# between one and ten, if it's between those numbers then change the
# text to "Nice Choice!" else to first element of the list called lst
guess = int(input("Enter a number (1 - 10): "))
if 1 <= guess <= 10:
c.configure(text="Nice choice!")
else:
c.configure(text=f"{lst[0]}") # Using f string
root.mainloop()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/477339.html
上一篇:按鈕不顯示tkinter
下一篇:我正在嘗試從tkinter中的單選按鈕獲取值,但由于“NameError:名稱'var'未定義”而出現錯誤。下面是我的整個代碼。和
