首页 > 解决方案 > 如何检查单选按钮是否被选中但输入框在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()

标签: pythontkinter

解决方案


您可以使用以下方法测试输入字段是否包含文本:

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

让我知道我是否错过了这里的重点。:)


推荐阅读