对于屏幕上的键盘,我需要26个按钮,所有按钮都将键盘的一个字母添加到字符串中。我遇到的第一个问题是,按一个按钮后,字符串无法保存。例如,用户按“A”,“A”将被打印并应被存储。用户现在按“B”,“B”被打印,“A”消失。第二个问题是按钮只在第一次执行函数。下面是我的代码:
window = Tk()
window.attributes('-fullscreen', True)
window.configure(background='yellow')
master = Frame(window)
master.pack()
e = Entry(master)
e.pack()
e.focus_set()
nieuw_station = ""
def printanswer():
global nieuw_station
nieuw_station = e.get()
print(nieuw_station)
gekozen_station(nieuw_station)
invoeren = Button(master, text="Invoeren", width=10, command=printanswer)
invoeren.pack()
def letter_toevoegen(nieuw_station, letter):
nieuw_station += letter
print(nieuw_station)
return nieuw_station
a = Button(master, text="A", width=1, command=letter_toevoegen(nieuw_station, "a"))
a.pack()
b = Button(master, text="B", width=1, command=letter_toevoegen(nieuw_station, "b"))
b.pack()
window.mainloop()
预期的输出是:用户按“A”、“A”进行打印和存储。现在用户按“B”,“AB”将被打印并存储。最后用户按“C”,“ABC”现在被打印和存储。每当用户按下'inveren'按钮时,它将被发送到下一个函数,新的字符串作为参数(这实际上起作用了)。在
你有一些问题。首先,
command
要求传递一个函数,但传递的是函数的返回值。一种修复方法是将其包装在lambda
中:第二,我不知道}在做什么,字符串没有这些方法。在
nieuw_station.close()
和{第三,字符串是不可变的,因此当您在
letter_toevoegen
中执行nieuw_station += letter
操作时,这种变化不会在函数之外持续存在。在让它持久化的一种方法是使用
global nieuw_station
,然后可能无法将其传递给函数。在也就是说,当你看到一个
^{pr2}$global
语句时,有9次是使用类的更好方法。在这里,我们可以创建一个类来添加按钮并跟踪状态。在当然,我们也会在这里添加
^{3}$printanswer
,并添加“print answer”按钮等。使用该类的代码如下所示:这里有很多变体,你会看到它们到处浮动。(有些人喜欢
App
从tkinter.Tk
或其他tkinter小部件继承,其他人则将父部件传递给类,以便它可以知道将所有元素附加到何处,等等。)我要说明的一点是,如何将类用作数据的容器,而不是全局命名空间。在相关问题 更多 >
编程相关推荐