【问题标题】:tkinter Button to change an IntVar displayed in a Label [duplicate]tkinter 按钮更改标签中显示的 IntVar [重复]
【发布时间】:2020-02-13 19:08:57
【问题描述】:

似乎是一项简单的任务,但我以前从未使用过 tkinter,而且我的 Python 生锈了。

当我最初运行程序时会执行 print() 语句,但当我按下按钮时不会执行。我尝试了两种不同的按钮方法,但它们的行为方式相同。

该应用程序将用于将数据输入到 Excel 表中,但现在我已将问题简化为:


from tkinter import *
from tkinter import ttk

MAX_RECORDS=40


class MainWindow:
    def __init__(self,root):
        self.currentRow = IntVar()
        self.currentRow.set(2)

        self.label_record = Label(root,textvariable=self.currentRow)
        self.button_prev = ttk.Button(root,text="<--Previous",command=self.prev_record(self.currentRow))
        self.button_prev = ttk.Button(root,text="Next-->",command=self.next_record())
        self.label_record.grid(row=0,column=1)   
        self.button_prev.grid(row=0,column=2)     
        self.button_prev.grid(row=0,column=3)


    def prev_record(self,row):
        if row.get() > 1:
           row.set(row.get() - 1)
        print("<Row is {}".format(row.get()))

    def next_record(self):
        if self.currentRow.get() < MAX_RECORDS + 1:
            self.currentRow.set(self.currentRow.get() + 1)
        print(">Row is {}".format(self.currentRow.get()))


if __name__ == "__main__":
    root = Tk() 
    window=MainWindow(root)
    root.mainloop()

【问题讨论】:

标签: python tkinter


【解决方案1】:

您正在将按钮命令设置为调用下一个/上一个记录函数的结果,而不是函数本身。

改变

self.button_prev = ttk.Button(root,text="Next--&gt;",command=self.next_record())

self.button_prev = ttk.Button(root,text="Next--&gt;",command=self.next_record)

对于“上一个”按钮也是如此

【讨论】:

  • 谢谢,我现在看到了。我想我不能将参数传递给按钮命令。
  • @RyanN “我猜我过不了……”:你可以,看Python and Tkinter lambda function
猜你喜欢
  • 2020-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-10
相关资源
最近更新 更多