到目前为止,我在更改changeable_label字段中的文本时遇到问题我无法使用文本处理字符串,以便在单击radiobutton“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()
答案 0 :(得分:0)
尝试
changeable_label = Label(the_window, textvariable = label_colour)
让标签显示收音机选项的文本
我会重命名label_colour
,因为它不是颜色而是方向。
还可以将您的代码更改为使用dictionairy。
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)
。
答案 1 :(得分:0)
回答了我自己的问题,我无法相信我 我之前没有看到这个......
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'