按钮超出命令一次(Tkinter)

2024-09-29 17:51:34 发布

您现在位置:Python中文网/ 问答频道 /正文

对于屏幕上的键盘,我需要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'按钮时,它将被发送到下一个函数,新的字符串作为参数(这实际上起作用了)。在


Tags: 字符串text用户masterbutton键盘windowwidth
1条回答
网友
1楼 · 发布于 2024-09-29 17:51:34

你有一些问题。首先,command要求传递一个函数,但传递的是函数的返回值。一种修复方法是将其包装在lambda中:

a = Button(master, text="A", width=1, command=lambda: letter_toevoegen(nieuw_station, "a"))
a.pack()

第二,我不知道nieuw_station.close()和{}在做什么,字符串没有这些方法。在

第三,字符串是不可变的,因此当您在letter_toevoegen中执行nieuw_station += letter操作时,这种变化不会在函数之外持续存在。在

让它持久化的一种方法是使用global nieuw_station,然后可能无法将其传递给函数。在


也就是说,当你看到一个global语句时,有9次是使用类的更好方法。在这里,我们可以创建一个类来添加按钮并跟踪状态。在

^{pr2}$

当然,我们也会在这里添加printanswer,并添加“print answer”按钮等。使用该类的代码如下所示:

^{3}$

这里有很多变体,你会看到它们到处浮动。(有些人喜欢Apptkinter.Tk或其他tkinter小部件继承,其他人则将父部件传递给类,以便它可以知道将所有元素附加到何处,等等。)我要说明的一点是,如何将类用作数据的容器,而不是全局命名空间。在

相关问题 更多 >

    热门问题