【问题标题】:TypeError: can only concatenate str (not "tuple") to strTypeError: 只能将 str(而不是 \"tuple\")连接到 str
【发布时间】:2022-11-01 15:38:47
【问题描述】:

我正在尝试制作密码生成器。我收到错误:TypeError: can only concatenate str (not "tuple") to str

我试过的:

原来的

def generate():
    lbl.config(text = "Password Generated: " + password)

已编辑(仍然无法正常工作)

def generate():
    lbl.config(text = ("Password Generated: " + password))

这是完整的脚本:

#imports
import tkinter as tk
import string
import random

#Password Generator
c1 = random.choice(string.ascii_letters)
c2 = random.choice(string.ascii_letters)
c3 = random.choice(string.ascii_letters)
c4 = random.choice(string.ascii_letters)
c5 = random.choice(string.ascii_letters)
c6 = random.choice(string.ascii_letters)
c7 = random.choice(string.ascii_letters)
c8 = random.choice(string.ascii_letters)
c9 = random.choice(string.ascii_letters)
c10 = random.choice(string.ascii_letters)
s1 = random.choice(string.punctuation)
n1 = random.randint(0,9)
n2 = random.randint(0,9)
n3 = random.randint(0,9)

password = (c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, s1, n1, n2, n3)

#Setting up Window
frame = tk.Tk()
frame.title("Random Password Generator")
frame.geometry("1280x720")

#Label
lbl = tk.Label(frame, text = " ")
lbl.pack()
frame.mainloop()

#Function : Generator
def generate():
    lbl.config(text = ("Password Generated: " + password))
    
#Button - Generate
genButton = tk.Button(frame,
                        text = "Generate",
                        command = generate())
genButton.pack()

#execute1

generate()

【问题讨论】:

  • 使用''.join(map(str, password))
  • 密码似乎是一个元组,而不是一个字符串。 (a,b,c) 是一个元组,"abc" 是一个字符串。
  • 谢谢你有帮助

标签: python


【解决方案1】:

该错误是有道理的,因为您试图将str 对象与tuple 对象连接起来。

def generate():
    lbl.config(text = ("Password Generated: " + password))
                       ^^^^^^^^^^^^^^^^^^^^     ^^^^^^^^^
                                |                    |
                                |                    |
                               String object        Tuple object

我认为您打算从元组创建一个字符串对象,您可以使用 .join 方法来完成。

def generate():
        lbl.config(text = ("Password Generated: " + "".join(str(p) for p in password))) 
                                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

【讨论】:

  • 我现在得到这个: TypeError: sequence item 11: expected str instance, int found
猜你喜欢
  • 2020-09-18
  • 2020-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-15
  • 2021-02-06
  • 1970-01-01
相关资源
最近更新 更多