【问题标题】:Update text widget in tkinter from function从函数更新 tkinter 中的文本小部件
【发布时间】:2021-06-09 17:55:26
【问题描述】:

问题:

我正在尝试从包含一些文本的函数更新相同的文本小部件框。相反,每次都会出现一个全新的文本窗口。

这是我的代码:

from tkinter import *
import os

#Tkinter graphics

homepage = Tk()
homepage.title("My first GUI")
# set size of window
homepage.geometry('1200x400')
# Add image file 
bg = PhotoImage(file = "maxresdefault.png") 
    
# Show image using label 
label1 = Label( homepage, image = bg) 
label1.place(x = 0, y = 0) 

label2 = Label( homepage, text = "Test App") 
label2.pack() 

# Create Frame 
frame1 = Frame(homepage) 
frame1.pack()

#button initatiors
def buttonupdate():
    S = Scrollbar(homepage)
    T = Text(homepage, height=100, width=30)
    T.pack()
    T.pack(side=RIGHT, fill= Y)
    S.pack(side = RIGHT, fill = Y)
    S.config(command=T.yview)
    T.insert(END, "test")
    T.config(yscrollcommand=S.set, state=DISABLED)


    

# Static buttons
tickets30button = Button(text = "This is button 1", command=buttonupdate) 
tickets30button.place(x=0, y=26) 

mcibutton = Button(text = "This is button 2") 
mcibutton.place(x=0, y=52)

hdebutton = Button(text = "This is button 3")
hdebutton.place(x=0, y=78)

homepage.mainloop()

如果我点击第一个按钮三次,结果如下:

如果您有任何我可以尝试的建议,请告诉我。

感谢您的宝贵时间,

【问题讨论】:

  • 每次调用函数时都会创建一个新的Text 小部件。将函数的前 5 行移到函数之外,它应该可以工作
  • 另外你为什么打电话给T.pack() 然后T.pack(side=RIGHT, fill= Y)?只要有T.pack(side=RIGHT, fill= Y)
  • @TheLizzard 完全有效。我删除了 T.Pack() 并从函数中取出前五行并将其放在函数上方并且它可以工作!文本小部件将在我现在单击按钮之前出现,但如果它不是每次都创建新窗口,那对我来说很酷。大声笑再次感谢。
  • 你可以删除这个问题或者回答它或者@TheLizzard可以回答它。
  • @CoolCloud 在我看来,删除问题并不是一个好习惯。其他人可能有同样的问题,偶然发现了这个问题并找到了解决方案,即使它在 cmets 中。

标签: python function tkinter widget


【解决方案1】:

感谢@TheLizzard,我能够在每次单击按钮时更新我的​​文本窗口,而不是创建一个新窗口。

他提到将创建文本窗口的代码部分移到函数之外,并将创建文本的代码部分保留在函数内部。

之前:

#button initiators
def buttonupdate():
    S = Scrollbar(homepage)
    T = Text(homepage, height=100, width=30)
    T.pack()
    T.pack(side=RIGHT, fill= Y)
    S.pack(side = RIGHT, fill = Y)
    S.config(command=T.yview)
    T.insert(END, "test")
    T.config(yscrollcommand=S.set, state=DISABLED)

之后:(更新)

S = Scrollbar(homepage)
T = Text(homepage, height=100, width=30)
T.pack(side=RIGHT, fill= Y)
S.pack(side = RIGHT, fill = Y)
S.config(command=T.yview)
T.config(yscrollcommand=S.set, state=DISABLED)

#button initatiors
def myTicketstatusbutton():
    T.delete(1.0,END)
    T.insert(END, "test")
    

【讨论】:

  • 您还可以将 S.config(command=T.yview)T.config(yscrollcommand=S.set, state=DISABLED) 移到函数之外以使其更快。
  • 另外T.pack_forget() 没有做任何事情,所以你可以删除它(它不会影响实际代码)
  • 啊,是的,我忘了删除 T.pack_forget() 。谢谢你抓住那个。我也更改了答案以反映新信息。再次感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多