我正在尝试根据2个问题的答案制作我的第一个GUI脚本。我将展示非GUI脚本的示例
while True:
ammount = input("What is your debt")
if ammount.isdigit() == True:
break
else:
print("Please try typing in a number")
while True:
month = input("In which month did the debt originate?")
if month not in ["January", "February"]:
print("Try again")
else:
break
这个脚本的重点在于它可以扩展,可以添加所有问题,我想在Tkinter中以相同的方式理解它。我会展示我尝试过的东西:
from tkinter import *
def click():
while True:
entered_text = text_entry.get()
if entered_text .isdigit() == False:
error = Label(window, text="Try again", bg = "black", fg="red", font="none 11").grid(row = 3, column = 2, sticky= W).pack()
else:
break
return True
window = Tk()
window.title("Tax calculator")
window.configure(background="black")
monto = Label(window, text="¿What is your debt?", bg="black", fg="white", font="none 12 bold")
monto.grid(row = 1, column = 0, sticky= W)
text_entry = Entry(window, width = 20, bg="white")
text_entry.grid(row = 2, column=2, sticky=W)
output = Button(window, text = "Enter", width = 6, command = click)
output.grid(row = 3, column = 0, sticky = W)
问题是,我无法在click()方法的if / else中添加Label()方法,因为一旦条件满足,我想问一个新问题。一旦满足条件,我也无法从单击中获取True
,因为输入来自Button()方法。提前致谢
答案 0 :(得分:0)
这里你实际上并不需要任何循环,一个简单的if语句足以完成这个技巧。此外,无需每次都重新创建标签,您只需configure()
其文本即可。并且,请注意索引从0开始 - 所以,在你的网格中,实际的第一行(和列)需要编号为0,而不是1.除此之外,我建议你摆脱import *
,因为你不要知道进口的名称。它可以替换您之前导入的名称,这使得很难看到程序中的名称应该来自哪里。您可能还想阅读PEP8 says about spaces around keyword arguments:
import tkinter as tk
def click():
entered_text = text_entry.get()
if not entered_text.isdigit():
status_label.configure(text='Please try again')
text_entry.delete(0, tk.END)
else:
status_label.configure(text='Your tax is ' + entered_text)
text_entry.delete(0, tk.END)
root = tk.Tk()
root.title('Tax calculator')
root.configure(background='black')
monto = tk.Label(root, text='¿What is your debt?', bg='black', fg='white', font='none 12 bold')
monto.grid(row=0, column=0, padx=10, pady=(10,0))
text_entry = tk.Entry(root, width=20, bg='white')
text_entry.grid(row=1, column=0, pady=(10,0))
status_label = tk.Label(root, text='', bg='black', fg='red', font='none 11')
status_label.grid(row=2, column=0)
button = tk.Button(root, text='Enter', width=17, command=click)
button.grid(row=3, column=0, pady=(0,7))
root.mainloop()
我忘了提一下,如果你的应用程序越来越大,你最好不要上课。