tkinter 网格识别不起作用,无法识别每个像素

我知道这是一个非常个别的问题,但我认为这是 Tkinter 中的一个问题,因为我经常遇到类似的问题,我解决了这些问题,答案也可能对其他人有益。


脚本是:


from tkinter import *

import random


class gui:

  def __init__(self):

    win=self.win=Tk()

    win.title('Ploters Data!')

  def identifier(self,x,y):

    print('id',x,y) 

    

  def createGraph(self,rows,columns):

    for xrow in range(rows+1):

      for ycolumn in range(columns+1):

        if xrow == 0 or ycolumn == 0:

          text = '--'

          if xrow == 0:

            if ycolumn==5:

              text='5'

            if ycolumn==10:

              text='10'  

          if ycolumn == 0:

            if xrow==5:

              text='5'

            if xrow==10:

              text='10'

          if xrow == ycolumn == 0:

              text='[]'

          pixel = Button(self.win,padx=10,pady=10,text=text)

          # print('click',xrow,ycolumn)

          pixel.config(command=lambda button=pixel: self.identifier(xrow,ycolumn))

          pixel.grid(row=xrow,column=ycolumn)

        else:

          pixel = Button(self.win,padx=10,pady=10)

          # print('click',xrow,ycolumn)

          pixel.config(command=lambda button=pixel: self.identifier(xrow,ycolumn))

          pixel.grid(row=xrow,column=ycolumn)

        # print(xrow,ycolumn)

    self.win.mainloop()


s=gui()

s.createGraph(15,10)

具体问题是,当您单击网格上的按钮时,它不会给出正确的“坐标”,而是给出最后一个按钮。


慕姐8265434
浏览 98回答 1
1回答

湖上湖

我想你覆盖了 lambda 函数,它在这个例子中是可变的。我不知道为什么会发生这种情况(tkinter GUI 也有同样的问题)但我现在知道一个简单的解决方法。如果您定义一个类,它接受一个函数和一系列参数和关键字参数,并且只使用这些参数调用该函数,您可以将它作为按钮中的命令引用。使用此解决方法,您可以省略 lambda 并仅调用带参数的函数:from tkinter import *import randomclass CMD: #Auxilliary function for callbacks using parameters. Syntax: CMD(function, argument1, argument2, ...)    def __init__(s1, func, *args):        s1.func = func        s1.args = args    def __call__(s1, *args):        args = s1.args+args        s1.func(*args)class gui:  def __init__(self):    win=self.win=Tk()    win.title('Ploters Data!')  def identifier(self,x,y):    print('id',x,y)       def createGraph(self,rows,columns):    for xrow in range(rows+1):      for ycolumn in range(columns+1):        if xrow == 0 or ycolumn == 0:          text = '--'          if xrow == 0:            if ycolumn==5:              text='5'            if ycolumn==10:              text='10'            if ycolumn == 0:            if xrow==5:              text='5'            if xrow==10:              text='10'          if xrow == ycolumn == 0:              text='[]'          pixel = Button(self.win,padx=10,pady=10,text=text,command=CMD(self.identifier,xrow,ycolumn))          pixel.grid(row=xrow,column=ycolumn)        else:          pixel = Button(self.win,padx=10,pady=10,command=CMD(self.identifier,xrow,ycolumn))          pixel.grid(row=xrow,column=ycolumn)        # print(xrow,ycolumn)    self.win.mainloop()s=gui()s.createGraph(15,10)使用这个小改动,您的程序可以正常工作。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python