import tkinter as tk
CENTER=tk.CENTER
NW=tk.NW
root=tk.Tk()
canvas1 = tk.Canvas(root, width = 450, height = 500)
canvas1.pack()
#Function to be called when button is clicked
def getImage(t_entry):
if(t_entry.get().lower()=="Hello"):
photo=tk.PhotoImage(file="C:\\Users\Alpha\PycharmProjects\Challenge1\Assets\Image2.jpg")
canvas1.create_image(225,210, anchor=NW, image=photo)
elif(t_entry.get().lower()=="My Name is"):
photo=PhotoImage(file="C:\\Users\Alpha\PycharmProjects\Challenge1\Assets\Image1.png")
canvas1.create_image(225,210, anchor=NW, image=photo)
label1 = tk.Label(root, text='Text to Sign Language Interpretation')
label1.place(relx=.5,rely=.5,anchor=CENTER)
label1.config(font=('helvetica', 14))
canvas1.create_window(225, 25, window=label1)
label2 = tk.Label(root, text='Type Your Text:')
label2.place(relx=.5,rely=.5,anchor=CENTER)
label2.config(font=('helvetica', 14))
canvas1.create_window(225, 100, window=label2)
#Entry for user to enter text they want displayed in sign langauage
entry1 = tk.Entry (root)
canvas1.create_window(225, 140, window=entry1)
#Button that Displays Sign Language Image
button1 = tk.Button(text='Show Sign Language', command=getImage(entry1), bg='grey', fg='white', font=('helvetica', 9, 'bold'))
canvas1.create_window(225, 190,anchor=CENTER, window=button1)
root.mainloop()
當用戶輸入分配給該影像的文本時,應用程式會顯示手語影像。例如,如果用戶輸入“你好”,它會以手語顯示“你好”的影像。
uj5u.com熱心網友回復:
您的代碼中有幾個問題:
command=getImage(entry1)將getImage()立即執行,而不是單擊按鈕。command=lambda: getImage(entry1)改為使用t_entry.get().lower()=="Hello"將始終是False左側全小寫,但右側不是。同上t_entry.get().lower()=="My Name is"。建議將右側也改為全部小寫。影像將被垃圾收集,如本問題所述。您可以創建
photo一個全域變數來修復它。getImage()每當執行時,您都會創建新的影像項。最好創建一次影像項并在函式內更新其影像。
以下是解決上述問題所需的更改代碼:
...
def getImage(t_entry):
global photo # avoid garbage collection by using global variable
if t_entry.get().lower() == "hello": # changed to all lowercase
photo = tk.PhotoImage(file="C:\\Users\Alpha\PycharmProjects\Challenge1\Assets\Image2.jpg")
canvas1.itemconfigure(image_id, image=photo) # update image item
elif t_entry.get().lower() == "my name is": # change to all lowercase
photo = PhotoImage(file="C:\\Users\Alpha\PycharmProjects\Challenge1\Assets\Image1.png")
canvas1.itemconfigure(image_id, image=photo) # update image item
else:
# clear the image if text cannot be matched to an image
canvas1.itemconfigure(image_id, image='')
...
# used command=lambda: getImage(entry)
button1 = tk.Button(text='Show Sign Language', command=lambda: getImage(entry1), bg='grey', fg='white', font=('helvetica', 9, 'bold'))
canvas1.create_window(225, 190, anchor=CENTER, window=button1)
# create the image item initially without a image
image_id = canvas1.create_image(225, 210, anchor=NW)
root.mainloop()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/443941.html
上一篇:型別錯誤:askstring()缺少1個必需的位置引數:“提示”
下一篇:通過命令制作時,如何更改按鈕列?
