python - 如何检查单选按钮是否被选中但输入框在tkinter中为空?
问题描述
我想在我的 tinkter 应用程序中完成这种前卫的场景。我的 tinkter 应用程序的工作方式是:用户需要输入一些文本。然后选择一个单选按钮选项。一旦用户选择单选按钮选项,就会计算一些值。现在这是边缘情况。基本上,如果用户在不输入值的情况下选择单选选项,我想在输入框下方显示错误消息“您需要在输入框中输入值”。
这是我的代码的样子:
from tkinter import *
class GetInterfaceValues():
def __init__(self):
self.root = Tk()
self.totalValue = StringVar()
self.root.geometry('900x500')
self.RadioText = StringVar()
self.getPeg = Button(self.root, text='calculate kegs values', command=self.findPeg)
self.quarterlyTextString = 'Keg'
self.yearlyTextString = 'parKeg'
self.textInputBox = Text(self.root, relief=RIDGE, height=1, width=6, borderwidth=2)
self.frequencyText = Label(self.root, text="Frequency")
self.normalKegRadioButton = Radiobutton(self.root, text="normal Keg", variable=self.RadioText,
value=self.quarterlyTextString, command=self.selectedRadioButtonOption)
self.parRadioButton = Radiobutton(self.root, text="Par Kegs", variable=self.RadioText, value=self.yearlyTextString,
command=self.selectedRadioButtonOption)
self.clearButton = Button(self.root, text="Clear",command=self.clear)
self.textInputBox.pack()
self.normalKegRadioButton.pack()
self.parRadioButton.pack()
self.getPeg.pack()
self.clearButton.pack()
self.root.mainloop()
def selectedRadioButtonOption(self):
radioButtonFrequencyOption = self.RadioText.get()
if(radioButtonFrequencyOption == self.quarterlyTextString):
self.findPeg()
if(radioButtonFrequencyOption == self.yearlyTextString):
print(self.yearlyTextString)
def getTextInput(self):
result = self.textInputBox.get("1.0", "end")
results = result.upper()
results = results.rstrip()
results = int(results)
return results
def clear(self):
self.parRadioButton.deselect()
self.normalKegRadioButton.deselect()
self.textInputBox.delete("1.0", "end")
def findPeg(self):
userInput = self.getTextInput()
lab = userInput * 15
print(lab)
app = GetInterfaceValues()
app.mainloop()
解决方案
您可以使用以下方法测试输入字段是否包含文本:
if len(entry.get()) > 0:
每当单选按钮(或条目)更改时,您还可以调用函数:
myradiobutton = Radiobutton(root, command = thefunction)
此外,您可以通过以下方式以编程方式取消选择单选按钮:
myradiobutton.deselect()
如果这有帮助。
把它放在一起你可以做这样的事情:
def getinput():
if len(entry.get()) > 0:
#do whatever you want to do with the input
else:
radiobutton.deselect()
#display your "enter something" message
entry = Entry(root)
radiobutton = Radiobutton(root, text = "Click when done typing", command = getinput)
entry.pack()
radiobutton.pack()
让我知道我是否错过了这里的重点。:)
推荐阅读
- c# - 无法读取所有串行端口数据,波特率 3000000
- kotlin - Kotlin - 对象过滤器列表
- java - 互联网连接恢复后,Firestore 快照侦听器仅提供最后一项
- html - 在 CodeIgniter 中保存不完整的数据(视图到控制器)
- python - 如何在熊猫中将日期索引拆分为单独的日、月、年列
- firebase - 识别从本地服务或托管到云后调用的 Firebase 函数
- reactjs - 如何使用 onPress 或 onClick 事件更改 Material Icon?
- ruby-on-rails-5 - 没有在延迟作业适配器的活动作业中获取 provider_job_id
- javascript - 在 XSLT 中使用子标签值对父标签进行排序
- wordpress - Wordpress 从带有自定义模板的插件创建页面