如何使用函数将变量分配给tkinter的输入框

时间:2018-08-31 02:53:40

标签: python tkinter

在我解释问题之前,这里是一个代码示例。

from tkinter import *
from tkinter import messagebox


class Add:

    def __init__(self, master):
        self.frame = Frame(master)
        self.frame.grid()

        self.entry_1 = Entry(self.frame)
        self.entry_1.grid(row=0, column=0)

        self.entry_2 = Entry(self.frame)
        self.entry_2.grid(row=1, column=0)

        self.button = Button(self.frame, text='Submit', command=self.submit)
        self.button.grid(row=0, column=1)

    def submit(self):
        # Checks if both entries are digits.
        if self.entry_1.get().isdigit() is False:
            messagebox.showerror('Error', 'Invalid Character(s).')
        elif self.entry_2.get().isdigit() is False:
            messagebox.showerror('Error', 'Invalid Character(s).')

        add_entry_1_and_2 = int(self.entry_1.get()) + int(self.entry_2.get())
        print(add_entry_1_and_2)


root = Tk()
Add(root)
root.mainloop()

只要我为两个输入框分配了一个数字,此代码就可以很好地工作,但是如果我将其中一个输入框留空并按提交按钮,则会引发此错误。

ValueError: invalid literal for int() with base 10: ''

我想要的是如果其中一个框保留为空,我想将该空框分配为0。如何实现呢?

1 个答案:

答案 0 :(得分:0)

您可以在每个输入字段中将默认值设置为零,并在提交时重置此值。
然后,您可以在try-except块中检查输入值的有效性,并仅在它们符合时才继续添加值,否则,引发触发Error弹出窗口的异常。

也许是这样吗?

from tkinter import *
from tkinter import messagebox


class Add:

    def __init__(self, master):
        self.frame = Frame(master)
        self.frame.grid()

        self.default_value = '0'
        self.entry_1 = Entry(self.frame)
        self.entry_1.grid(row=0, column=0)

        self.entry_2 = Entry(self.frame)
        self.entry_2.grid(row=1, column=0)

        self.button = Button(self.frame, text='Submit', command=self.submit)
        self.button.grid(row=0, column=1)

        self.reset_entry_defaults()

    def reset_entry_defaults(self):
        self.entry_1.delete(0,END)
        self.entry_2.delete(0,END)
        self.entry_1.insert(0, self.default_value)
        self.entry_2.insert(0, self.default_value)

    def submit(self):
        try:
            e1 = int(self.entry_1.get())   # <-- you may prefer to convert to float
            e2 = int(self.entry_2.get())   # <-- you may prefer to convert to float
        except ValueError:
            messagebox.showerror('Error', 'Invalid Character(s).')
        else:
            add_entry_1_and_2 = e1 + e2
            print(add_entry_1_and_2)
        self.reset_entry_defaults()


root = Tk()
Add(root)
root.mainloop()

(可选)您可以将class Add继承自tk.Frame(是tk.Frame),并执行以下操作:

import tkinter as tk                   # <-- avoid star imports
from tkinter import messagebox


class Add(tk.Frame):                   # <-- inherit from tk.Frame

    def __init__(self, master):
        self.master = master
        super().__init__(self.master)  # <-- call the parent class

        self.default_value = '0'
        self.entry_1 = tk.Entry(self)
        self.entry_1.grid(row=0, column=0)

        self.entry_2 = tk.Entry(self)
        self.entry_2.grid(row=1, column=0)

        self.button = tk.Button(self, text='Submit', command=self.submit)
        self.button.grid(row=0, column=1)

        self.reset_entry_defaults()

    def reset_entry_defaults(self):
        self.entry_1.delete(0, tk.END)
        self.entry_2.delete(0, tk.END)
        self.entry_1.insert(0, self.default_value)
        self.entry_2.insert(0, self.default_value)

    def submit(self):
        try:
            e1 = int(self.entry_1.get())
            e2 = int(self.entry_2.get())
        except ValueError:
            tk.messagebox.showerror('Error', 'Invalid Character(s).')
        else:
            add_entry_1_and_2 = e1 + e2
            print(add_entry_1_and_2)
        self.reset_entry_defaults()


root = tk.Tk()
Add(root).grid()    # <-- call the tk geometry manager to place your frame in root
root.mainloop()