3

文字列「currentMessage」とそれを表示するラベルがあります。「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()

この関数を使用して、トップレベルの「textBox」テキストウィジェットのコンテンツを取得しようとしました:

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

しかし、私はエラーが発生しました

「トップレベル」オブジェクトには属性「textBox」がありません

では、'popup' の子ウィジェットであるウィジェット 'textBox' のコンテンツにアクセスするにはどうすればよいでしょうか (このトップレベル ウィジェットは関数 changeValues() が呼び出されたときにのみ作成されます)。

4

2 に答える 2

2

おそらくこれがあなたが探しているものだと思います -- ただ推測していますが、あなたが抱えていると思われる特定の問題の解決策を求めているからです。 :

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()
于 2013-11-08T06:41:50.093 に答える
-1

実際には次のような方法があります。

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

def changeValues():
    popup = Toplevel(mainFrame)
    popup.grid()
    textBox = Text(popup, width = 20, height = 5, name = 'textBox')
    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'

「名前」は好きなものを選べます。

于 2018-12-16T03:46:15.560 に答える