如何根据用户输入更改窗口内容?

时间:2015-04-02 03:25:15

标签: python tkinter

假设我有一个看起来像这样的窗口:

http://i.stack.imgur.com/6ATUN.png

根据用户点击的内容(是或否),不使用Toplevel(),将同一窗口的内容更改为:

http://i.stack.imgur.com/keD9k.png

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

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()

1 个答案:

答案 0 :(得分:0)

您可以将回调功能附加到按钮上,这些按钮会更改每个按钮的文字,如下所示:

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字典中的值来更改每个按钮的文本。


修改

对于简单的条款和条件表单,您可以执行以下操作。这启用/禁用"继续"单击/清除复选框时按钮。它还会填充文本框(您已经在那里)并禁用它以使其不可编辑。

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()