本文介绍了bind python measure() 完全采用位置参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Tkinter 在 python 中制作了一个简单的 GUI.我写它是为了当一个按钮被按下时一个函数(测量)被调用.我现在正在尝试绑定 Enter 键以使用以下方法执行此功能:

I have made a simple GUI in python using Tkinter.I've written it so that when a button is pressed a function (measure) is called.I'm now trying to bind the Enter key to also carry out this function using:

root.bind("<Return>", measure)

这在按下 Enter 时会出现错误:

This gives the error when Enter is pressed:

TypeError: measure() takes no arguments (1 given)

快速搜索告诉我,如果我为函数提供参数 (self),则输入绑定将起作用,但是如果我这样做,则按钮小部件会给出错误:

A quick search tells me that if I give the function the argument (self) then the enter bind will work, however if I do this then the button widget gives the error:

TypeError: measure() takes exactly 1 positional argument (0 given)

是否有快速解决方法?Python初学者,如果这是一个非常简单的问题,请道歉.

Is there a quick fix for this?Python beginner, so apologies if this is a really simple question.

import datetime
import csv
from tkinter import *
from tkinter import messagebox


root = Tk()

winx = 480
winy = 320 

virtual_reading = '1.40mm'        

def measure():
    todays_date = datetime.date.today()

    try:
        get_tool_no = int(tool_no_entry.get())
        if get_tool_no <= 0:
            messagebox.showerror("Try Again","Please Enter A Number")
        else:
            with open("thickness records.csv", "a") as thicknessdb: 
                thicknessdbWriter = csv.writer(thicknessdb, dialect='excel', lineterminator='\r')
                thicknessdbWriter.writerow([get_tool_no] + [todays_date] + [virtual_reading])
            thicknessdb.close()
    except:
           messagebox.showerror("Try Again","Please Enter A Number")
    tool_no_entry.delete(0, END)            

root.resizable(width=FALSE, height=FALSE) 
root.geometry('%dx%d' % (winx,winy)) 
root.title("Micrometer Reader V1.0")         

record_button = Button(root,width = 30,
                               height = 8,
                               text='Measure',
                               fg='black',
                               bg="light grey", command = measure)

record_button.place(x = 350, y = 100, anchor = CENTER)

reading_display = Label(root, font=("Helvetica", 22), text = virtual_reading)
reading_display.place(x = 80, y =80)

tool_no_entry = Entry(root)
tool_no_entry.place(x = 120, y = 250, anchor=CENTER)
tool_no_entry.focus_set()

root.bind("<Return>", measure)

root.mainloop()

推荐答案

command 不带参数调用 measurebind 调用>event 参数所以 measure 必须接收这个值.

command calls measure without arguments but bind calls it with event argument so measure have to receive this value.

你可以使用

def mesaure(event=None): 

它将与 commandbind

这篇关于bind python measure() 完全采用位置参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 08:41