我正在嘗試在 Python Tkinter 中撰寫一個應用程式,您可以在其中通過文本欄位輸入文本,然后顯示輸入文本中每個字符的標簽。
from tkinter import *
array = []
root = Tk()
root.title('app interface')
inpframe = LabelFrame(root, text="input", padx=100, pady=20)
inpframe.pack()
outframe = LabelFrame(root, text="output", padx=100, pady=100)
outframe.pack()
c = " "
def on_enter(e):
e.widget['background'] = 'green'
c = e.widget['text']
currentchar = Label(inpframe, text=c)
currentchar.grid(row=1, column=1)
def on_leave(e):
e.widget['background'] = 'SystemButtonFace'
currentchar = Label(inpframe, text=" ")
currentchar.grid(row=1, column=1)
inp = Entry(inpframe)
inp.grid(row=0, column=0)
def enterText():
array.clear()
inptxt = inp.get().lower()
myLabel = Label(inpframe, text=inptxt)
myLabel.grid(row=1, column=0)
for i in inptxt:
array.append(i)
for i in range(0, len(array), 1):
array[i] = Button(outframe, text=array[i], height=10, width=5)
array[i].grid(row=2, column= i, padx=5, pady=10)
array[i].bind("<Enter>", on_enter)
array[i].bind("<Leave>", on_leave)
myButton = Button(inpframe, text="Enter", command=enterText)
myButton.grid(row=0, column=1)
root.mainloop()
這就是問題所在。當我輸入比前一個文本短的文本時,會顯示較短的文本,但前一個文本中的剩余文本仍保留在界面上 enter image description here。例如,當我鍵入“world”時,應用程式會顯示 worl d。但是當我輸入“hi”時,應用程式會顯示 hirld
uj5u.com熱心網友回復:
我看到保存文本的標簽也留在了新輸入的文本后面。您可以簡單地在全域范圍內創建標簽,然后在每次輸入新文本時配置文本。
至于按鈕;有一種簡單的方法可以銷毀小部件的所有子級,如下所示。
from tkinter import *
array = []
root = Tk()
root.title('app interface')
inpframe = LabelFrame(root, text="input", padx=100, pady=20)
inpframe.pack()
outframe = LabelFrame(root, text="output", padx=100, pady=100)
outframe.pack()
inp = Entry(inpframe)
inp.grid(row=0, column=0)
myLabel = Label(inpframe) # Create label in the global scope
myLabel.grid(row=1, column=0)
c = " "
def on_enter(e):
e.widget['background'] = 'green'
c = e.widget['text']
currentchar = Label(inpframe, text=c)
currentchar.grid(row=1, column=1)
def on_leave(e):
e.widget['background'] = 'SystemButtonFace'
currentchar = Label(inpframe, text=" ")
currentchar.grid(row=1, column=1)
def enterText():
array.clear()
inptxt = inp.get().lower()
myLabel.config(text=inptxt) # Configure label for new text
# Delete all current buttons
for widget in outframe.winfo_children():
widget.destroy()
for i in inptxt:
array.append(i)
for i in range(0, len(array), 1):
array[i] = Button(outframe, text=array[i], height=10, width=5)
array[i].grid(row=2, column= i, padx=5, pady=10)
array[i].bind("<Enter>", on_enter)
array[i].bind("<Leave>", on_leave)
myButton = Button(inpframe, text="Enter", command=enterText)
myButton.grid(row=0, column=1)
root.mainloop()
或者,您可以在清除陣列之前回圈遍歷陣列并洗掉每個按鈕:
# Delete all current buttons
for i in array:
i.destroy()
array.clear()
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/461132.html
上一篇:tkinter語法理解
下一篇:如何讓影像統一放入面板中
