如何根据用户输入更改 window 的内容?

How to change contents of a window depending on user input?

假设我有一个 window 看起来像这样:

并且根据用户点击的内容(是或否),在不使用 Toplevel() 的情况下,将相同 window 的内容更改为:

我该如何编码这种情况?我会使用 类 吗?或者我会使用调用新内容的函数吗?

Windows 的代码:

root = Tk()
frame = Frame(root)
label = Label(frame , text='Example/Change')
textbox = Text(frame)
textbox.insert
button1 = Button(frame , text='Yes/Ok')
button2 = Button(frame , text='No/Cancel')

frame.pack()
label.pack( padx=20 , pady=5 )
button1.pack( padx=10 )
button2.pack( padx=10 )
root.mainloop()

您可以将回调函数附加到更改每个按钮文本的按钮,如下所示:

from Tkinter import *

toggle_text = {'Yes': 'OK',
               'No': 'Cancel',
               'OK': 'Yes',
               'Cancel': 'No'}

def toggle():
    button1['text'] = toggle_text[button1['text']]
    button2['text'] = toggle_text[button2['text']]

root = Tk()
frame = Frame(root)
label = Label(frame , text='Example')
textbox = Text(frame)
textbox.insert
button1 = Button(frame , text='Yes', command=toggle)
button2 = Button(frame , text='No', command=toggle)

frame.pack()
label.pack( padx=20 , pady=5 )
button1.pack( padx=10 )
button2.pack( padx=10 )
root.mainloop()

当一个按钮被点击时,它的回调函数被调用。在回调中,通过从 toggle_text 字典中查找值来更改每个按钮的文本。


编辑

对于简单的条款和条件表单,您可以执行如下操作。当复选框为 clicked/cleared 时,此 enables/disables 一个 "Continue" 按钮。它还会填充文本框(您已经在那里)并禁用它,使其不可编辑。

from Tkinter import *

def toggle_continue():
    if accept.get():
        button1.config(state=NORMAL)        # user agrees, enable button
    else:
        button1.config(state=DISABLED)

def cmd_cancel():
    print "User clicked cancel button"

def cmd_continue():
    print "User clicked continue button"


terms_and_conditions = '''Here are our long and unreadable terms and conditions.

We know that you won't read them properly, if at all, so just click the
"I accept" checkbox below, then click the 'Continue' button.'''

root = Tk()
frame = Frame(root)
label = Label(frame , text='Terms and conditions')

textbox = Text(frame)
textbox.insert(INSERT, terms_and_conditions)
textbox.config(padx=15, pady=15, state=DISABLED)

accept = IntVar()
accept_cb = Checkbutton(frame, text="I accept the terms and conditions",
                        variable=accept, command=toggle_continue)

button1 = Button(frame , text='Continue', command=cmd_continue, state=DISABLED)
button2 = Button(frame , text='Cancel', command=cmd_cancel)

frame.pack()
label.pack( padx=20 , pady=5 )
textbox.pack()
accept_cb.pack()
button1.pack( padx=10 )
button2.pack( padx=10 )
root.mainloop()