把同一个按钮和同一个命令放在多个地方,但有独特的功能

2024-10-02 02:33:03 发布

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

我不太清楚如何用一句话来表达我的问题。我正在使用python创建一个日历,可以记录运动员的里程数。我制作了一个日历,在左上角有一个7x4的网格,里面有一个月数,中间有一个按钮,上面写着“记录今天的训练”

该按钮应该打开一个新窗口,允许用户输入里程和跑多快,当用户按下新窗口底部的“日志”时,它应该显示该按钮按下当天的里程和速度。你知道吗

我的问题是我不知道如何仅用信息替换单击的特定日期。因为我不想为一个月的每一天制作一个按钮,所以我每天都有相同的按钮(以及相同的命令)。我需要的按钮,以知道它在网格中的位置,并能够告诉标签在哪里放置的里程和速度。你知道吗

我试过研究lambda,看看它是否有用,但没有用。下面是我的相关代码(对python还是相当陌生的,可能有点草率,我道歉)。你知道吗

 count = 0      #Code for button on every day in the month
    dayCounter = numDays[0]
    rowCount = 3
    while (numDays[1] > count):
        count = count + 1
        logButton = Button(self, text=("Log Today's Workout"), command = self.log)
        logButton.grid(column=dayCounter, row=rowCount)
        if dayCounter == 6:
            rowCount = rowCount + 1   
        if dayCounter <= 5:
            dayCounter = dayCounter + 1
        else:
            dayCounter = 0



def calculate(self): 
    displayPace = Label(self, text= paceMin + ":" + formattedSec + " a mile.")
    displayPace.grid(column=???, row=???)

我省略了很多代码。显示的是在每天上放置按钮的代码,以及在日历上放置速度的代码。我试过把一些东西排成行和列。我通常会收到错误消息,或者它会在每个框中放置相同的标签。我需要知道如何改变按钮或什么把行和列只替换按钮点击。如果有任何其他需要,我会检查这个非常频繁,并会经常更新。你知道吗


Tags: 代码text用户self网格count记录标签
2条回答

由于提供的代码很少,很难为您提供有效的解决方案;下面是我将采取的方法:

def log(self, event):
    x, y = event.x, event.y
    date_ = self._get_date_from_canvas_location(x, y)
    self.log_a_run(date_)

def _get_date_from_canvas_location(self, x, y):
    """returns the date corresponding to the canvas location clicked
    """
    # do the job
    return date_corresponding_to_that_location

def log_a_run(self, date_):
    """capture and save the run of of the date_
    """
    # do the job

通过上面的帖子和this one以及一些关于事件如何工作的研究(我从未听说过),我得出了以下结论:

grid_info = event.widget.grid_info()
self.displayRow = grid_info["row"]
self.displayColumn = grid_info["column"]

logButton = Button(self, text=("Log Today's Workout"))
logButton.grid(column=dayCounter, row=rowCount
logButton.bind('<Button-1>', self.log)

displayPace = Label(self, text= paceMin + ":" + formattedSec + " a mile.")
displayPace.grid(column=self.displayColumn, row=self.displayRow)

相关问题 更多 >

    热门问题