到目前为止,我在更改changeable_label字段中的文本时遇到了一个问题,当单击单选按钮'North-West‘时,我无法获得一个处理文本的字符串来将文本'Null’更改为NW。我不知道我是否需要创建另一个'if‘函数或者其他什么。
#Import the Tkinter functions
from Tkinter import *
# Creating the windo
the_window = Tk()
# Title of window
the_window.title('Change colour')
# Label widget which has its properties modified
changeable_label = Label(the_window, text = 'Null',
font = ('Times', 48), fg = 'black')
# String variables which values change on selcetion of radio button
label_colour = StringVar()
# Creating an a function to change the labels text colour when the radio
# button is chosen
def change_colour():
if label_colour.get() == 'NW':
changeable_label['fg'] = 'black',
elif label_colour.get() == 'NE':
changeable_label['fg'] = 'green'
elif label_colour.get() == 'SW':
changeable_label['fg'] = 'blue'
else:
changeable_label['fg'] = 'yellow'
# Creating an a function to change the labels text when the radio
# button is chosen
# Creating the frame for the 4 buttons.
colour_buttons = Frame(the_window)
# Creating the Radio Buttons features
NW_button = Radiobutton(colour_buttons, text = 'North-West',
variable = label_colour, value = 'NW',
command = change_colour)
NE_button = Radiobutton(colour_buttons, text = 'North-East',
variable = label_colour, value = 'NE',
command = change_colour)
SW_button = Radiobutton(colour_buttons, text = 'South-West',
variable = label_colour, value = 'SW',
command = change_colour)
SE_button = Radiobutton(colour_buttons, text = 'South-East',
variable = label_colour, value = 'SE',
command = change_colour)
# Placing the 4 radio buttons on specific rows, columns, locations.
NW_button.grid(row = 1, column = 1, sticky = W)
NE_button.grid(row = 2, column = 1, sticky = W)
SW_button.grid(row = 1, column = 2, sticky = W)
SE_button.grid(row = 2, column = 2, sticky = W)
# Using the geomtry manager to pack the widgets onto the window.
margin = 8 # pixels
changeable_label.pack(padx = margin, pady = margin)
colour_buttons.pack(padx = margin, pady = margin)
# Start the event loop to react to user inputs
the_window.mainloop()发布于 2014-05-04 23:46:53
试一试
changeable_label = Label(the_window, textvariable = label_colour)若要让标签显示单选选项的文本,请执行以下操作。
我会重命名label_colour,因为它不是颜色,而是方向。
你也可以改变你的代码来使用字典。
if label_colour.get() == 'NW':
changeable_label['fg'] = 'black',
elif label_colour.get() == 'NE':
changeable_label['fg'] = 'green'
elif label_colour.get() == 'SW':
changeable_label['fg'] = 'blue'
else:
changeable_label['fg'] = 'yellow'会变成
label_foreground = {'NW': 'black', "NE" : 'green', 'SW' : 'blue', 'SE' : 'yellow'}
changeable_label['fg'] = label_foreground[label_colour.get()]如果您愿意,您可以对文本执行相同的操作。与help(dict)一起阅读。
发布于 2014-05-06 08:01:30
回答我自己的问题,我不敢相信我没有早点看到这一点。
def change_text():
if label_text.get() == 'NW':
changeable_label['text'] = 'NW'
elif label_text.get() == 'NE':
changeable_label['text'] = 'NE'
elif label_text.get() == 'SW':
changeable_label['text'] = 'SW'
else:
changeable_label['text'] = 'SE'https://stackoverflow.com/questions/23455732
复制相似问题