gpt4 book ai didi

Python tkinter : access child widgets of a widget

转载 作者:太空宇宙 更新时间:2023-11-04 03:53:46 32 4
gpt4 key购买 nike

我有一个字符串 'currentMessage' 和一个用于显示它的标签。我有一个 Toplevel 小部件,其中包含一个文本小部件,为“currentMessage”提供新值:

from tkinter import *
from tkinter import ttk

root = Tk()
mainFrame = ttk.Frame(root)
mainFrame.grid()
currentMessage = 'current Message'
ttk.Label(mainFrame, text = currentMessage).grid(padx = 10, pady = 10)

def updateCurrentMessage(popupWindow):
currentMessage = popupWindow.textBox.get(0.0, END)

def changeValues():
popup = Toplevel(mainFrame)
popup.grid()
textBox = Text(popup, width = 20, height = 5)
textBox.grid(column = 0, row = 0)
textBox.insert(END, 'new message here')
b = ttk.Button(popup, command = lambda: updateCurrentMessage(popup))
b.grid(column = 0, row = 1, padx = 5, pady = 5)
b['text'] = 'Update'

theButton = ttk.Button(mainFrame, command = changeValues, text = 'Click')
theButton.grid(padx = 10, pady = 10)

mainFrame.mainloop()

我尝试使用此函数获取 Toplevel 的“textBox”文本小部件的内容:

def updateCurrentMessage(popupWindow):
currentMessage = popupWindow.textBox.get(0.0, END)

但是我得到了一个错误

'Toplevel' object has no attribute 'textBox'

那么如何访问小部件“textBox”的内容,它是“popup”的子小部件(此 Toplevel 小部件仅在调用函数 changeValues() 时创建)?

最佳答案

我想这可能就是您要找的东西——虽然我只是在猜测,因为您正在寻求针对您认为自己遇到的特定问题的解决方案,但是如果我是您,我会重新考虑我到底要做什么想做:

from tkinter import *
from tkinter import ttk

# Create Tk Interface root
root = Tk()

# Initialize mainFrame
mainFrame = ttk.Frame( root )
mainFrame.grid()

# Initialize label of mainframe
theLabel = ttk.Label( mainFrame, text='Current Message' )
theLabel.grid( padx=10, pady=10 )

def createPopup():
# Initialize popup window
popup = Toplevel( mainFrame )
popup.grid()
# Initialize text box of popup window
textBox = Text( popup, width=20, height=5 )
textBox.grid( column = 0, row = 0 )
textBox.insert( END, 'New Message Here' )
# Initialize button of popup window
button = ttk.Button( master = popup,
command = lambda: theLabel.config(text=textBox.get(0.0, END)),
text = 'Update')
button.grid( column=0, row=1, padx=5, pady=5 )

# Initialize button of main frame
theButton = ttk.Button( mainFrame, command=createPopup, text='Click' )
theButton.grid( padx=10, pady=10 )

# Enter event loop
mainFrame.mainloop()

关于Python tkinter : access child widgets of a widget,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19852245/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com