好的,所以脚本运行,你键入一个条目,按提交,弹出窗口显示键入的内容。我有两个问题想帮忙解决。空白提交并在点击提交后清除文本。
空白提交: 输入 1: 你好 输入 2: 世界 输入3: "无类型" 输入 4:你好世界 我在输入 3 上得到一个空行,但我不希望发生任何事情(不需要错误消息) 我尝试添加 .strip() 但这不起作用/我没有正确放入它,我在第 13 行的末尾尝试了它name=entry.get().strip
我尝试添加一行entry.strip()
清除文本:输入 1:欢迎输入 输入 2:到 输入 3:python 我必须手动擦除条目小部件的文本输入,然后才能键入下一行
import tkinter as tk
flag = False
win=""
def setflag(event):
global flag
flag = False
#function that prints the entry
def entry_function(e=None):
global flag,win
name = entry.get()
if not flag:
win = tk.Toplevel()
win.geometry('100x100')
win.bind('<Destroy>', setflag)
tk.Label(win, text=name).pack()
flag = True
win.geometry("+%d+%d" % (x + 600, y + 300))
else:
tk.Label(win, text=name).pack()
#Setup for the window
window = tk.Tk()
window.title("Title_Name")
window.geometry("500x500")
window.bind('<Return>', entry_function)
x = window.winfo_x()
y = window.winfo_y()
#widgets
label = tk.Label(window, text = "Manual:", bg = "dark grey", fg = "white")
entry = tk.Entry(window)
button = tk.Button(window,text = "submit",
command = entry_function)
#widget placement
label.place(x=0,y=20)
entry.place(x=52,y=21)
button.place(x=177, y=18)
window.mainloop()
对代码进行了一些更改(代码注释中的解释):
import tkinter as tk
# no need to use flag because just change win to None
# and check if it is None rather than using an
# additional variable
win = None
# this would set win variable to None
def set_win_none(event=None):
global win
win = None
def entry_function(event=None):
global win
name = entry.get()
# check if the string is empty, if so
# stop the function
if not name:
return
# clear the entry
entry.delete('0', 'end')
# as mentioned win can be used, it just shortens the code
if win is None:
win = tk.Toplevel()
# set geometry as needed, this
# will place the window
# on the right of the main window
win.geometry(f'100x100+{window.winfo_x() + window.winfo_width()}+{window.winfo_y()}')
win.bind('<Destroy>', set_win_none)
tk.Label(win, text=name).pack()
else:
tk.Label(win, text=name).pack()
window = tk.Tk()
label = tk.Label(window, text="Manual:", bg="dark grey", fg="white")
entry = tk.Entry(window)
button = tk.Button(window, text="submit", command=entry_function)
# better bind the return key to the entry since it is
# directly involved
entry.bind('<Return>', entry_function)
# very rarely do you need to use .place
# better use .grid or .pack
label.grid(row=0, column=0, padx=5)
entry.grid(row=0, column=1, padx=5)
button.grid(row=0, column=2, padx=5)
window.mainloop()
很少需要使用.place
,更好地使用.grid
或.pack
方法来放置小部件,它们更加动态并适应窗口的变化。
另外:
我强烈建议遵循PEP 8 - Python Code风格指南。函数和变量名应为snake_case
,类名应为CapitalCase
。如果它用作关键字参数的一部分(func(arg='value')
),则=
周围没有空格,但如果它用于分配值(variable = 'some value'
),则=
周围有空格。在运算符周围留出空间(+-/
等:value = x + y
(此处除外value += x + y
))。在函数和类声明周围有两个空行。