在Python中将元组转换为int

2024-05-21 02:30:36 发布

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

我是python的新手,不明白这个问题的其他答案。为什么当我运行代码时,int(weight[0])不将变量“weight”转换为整数。尽你最大的努力让它哑口无言,因为我真的是新来的,还不太明白其中的大部分。这是我的代码的相关部分

weight = (lb.curselection())
    print ("clicked")
    int(weight[0])
    print (weight)
    print (type(weight))

这是我的剧本代码

lb = Listbox(win, height=240)
lb.pack()
for i in range(60,300):
    lb.insert(END,(i))
def select(event):
    weight = (lb.curselection())
    print ("clicked")
    int(weight[0])
    print (weight)
    print (type(weight))
lb.bind("<Double-Button-1>", select)

谢谢

当我运行代码时,它会出现TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple' 我希望它能将“weight”变量转换成一个整数,这样我就可以用它进行数学运算了。

完整回溯:Traceback (most recent call last): File "C:\Users\Casey\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__ return self.func(*args) File "C:/Users/Casey/AppData/Local/Programs/Python/Python36-32/s.py", line 11, in select int(weight) TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple'


Tags: 代码intype整数beargumentselectint
2条回答

我注意到你在这里使用lb.bind("<Double-Button-1>", select)。这确实解决了curselection()返回最后一个选定列表项的问题,但我认为使用lb.bind('<<ListboxSelect>>', select)会更好地解决这个问题。绑定到<<ListboxSelect>>有效,因为此事件在所选内容更改后触发,并且当您使用此事件调用curselection()时,您将获得所需的正确输出。

下面是一段代码,提供了<<ListboxSelect>>事件的示例用法:

import tkinter as tk


class Application(tk.Frame):

    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        self.parent = parent
        self.lb = tk.Listbox(self.parent, height=4)
        self.lb.pack()
        self.lb.bind('<<ListboxSelect>>', self.print_weight)
        for item in ["one: Index = 0", "two: Index = 1", "three: Index = 2", "four: Index = 3"]:
            self.lb.insert("end", item)

    def print_weight(self, event = None):
        # [0] gets us the 1st indexed value of the tuple so weight == a number.
        weight = self.lb.curselection()[0] 
        print(weight)


if __name__ == "__main__":
    root = tk.Tk()
    app = Application(root)
    root.mainloop()

您将注意到控制台中的打印输出将是单击后的当前选定项。这将避免双击的需要。

你要找的是

weight = int(weight[0])

int是一个返回整数的函数,因此必须将该返回值赋给变量。

如果您要寻找的是用第一条记录的值重新分配变量weight,那么该代码应该适合您。

如果项已经是一个整数,那么int调用可能是多余的,您可以使用

weight = weight[0]

相关问题 更多 >