Python tkinter Entry widget status switch via Radio buttons

南楼画角 提交于 2021-02-07 14:44:27

问题


a simple question (not so simple for a tkinter newby like me): I'm building a GUI and I want to have two radio buttons driving the status (enabled or disabled) of an Entry widget, into which the user will input data. When the first radio button is pressed, I want the Entry to be disabled; when the second radio button is pressed, I want the Entry to be disabled.

Here is my code:

from Tkinter import *

root = Tk()
frame = Frame(root)

#callbacks
def enableEntry():
    entry.configure(state=ENABLED)
    entry.update()

def disableEntry():
    entry.configure(state=DISABLED)
    entry.update()

#GUI widgets
entry = Entry(frame, width=80)
entry.pack(side='right')

var = StringVar()
disableEntryRadioButton = Radiobutton(frame, text="Disable", variable=var, value="0", command=disableEntry)
disableEntryRadioButton.pack(anchor=W)
enableEntryRadioButton = Radiobutton(frame, text="Enable", variable=var, value="1", command=enableEntry)
enableEntryRadioButton.pack(anchor=W)

My idea is to invoke the proper callbacks when each radio button is pressed. But I'm not pretty sure that it actually happens with the code I wrote,because when I select the radios the status of the Entry is not switched.

Where am I wrong with it?


回答1:


You have a few things wrong with your program, but the general structure is OK.

  1. you aren't calling root.mainloop(). This is necessary for the event loop to service events such as button clicks, etc.
  2. you use ENABLED and DISABLED but don't define or import those anywhere. Personally I prefer to use the string values "normal" and "disabled".
  3. you aren't packing your main frame widget

When I fix those three things your code works fine. Here's the working code:

from Tkinter import *

root = Tk()
frame = Frame(root)
frame.pack()

#callbacks
def enableEntry():
    entry.configure(state="normal")
    entry.update()

def disableEntry():
    entry.configure(state="disabled")
    entry.update()

#GUI widgets
entry = Entry(frame, width=80)
entry.pack(side='right')

var = StringVar()
disableEntryRadioButton = Radiobutton(frame, text="Disable", variable=var, value="0", command=disableEntry)
disableEntryRadioButton.pack(anchor=W)
enableEntryRadioButton = Radiobutton(frame, text="Enable", variable=var, value="1", command=enableEntry)
enableEntryRadioButton.pack(anchor=W)

root.mainloop()


来源:https://stackoverflow.com/questions/6263226/python-tkinter-entry-widget-status-switch-via-radio-buttons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!