Tkinter:类型错误:+不支持的操作数类型:'int'和'str'

我试图在 python 中使用 tkinter 创建一个库:

import tkinter as tk

class Screen():
    def make_window(self, width: int=None, height: int=None, title: str=None) -> int:
        self.width = width
        self.height = height
        self.title = title
        new_window = tk.Tk()
        if width or height is not None:
            new_window.geometry(width + "x" + height)

win = Screen()
win.make_window()

它工作正常,我得到了这个漂亮的小窗口:

但如果我这样做:

import tkinter as tk

class Screen():
    def make_window(self, width: int=None, height: int=None, title: str=None) -> int:
        self.width = width
        self.height = height
        self.title = title
        global new_window
        new_window = tk.Tk()
        if width or height is not None:
            new_window.geometry(width + "x" + height)
    def mainloop(self) -> None:
        new_window.mainloop()

win = Screen()
win.make_window(500, 500)
win.mainloop()

我收到错误:

c:/Users/???/D
esktop/Leahnn Files/Python Projects/library/lib.py"
Traceback (most recent call last):
  File "c:/Users/????/Desktop/Leahnn Files/Python Projects/library/lib.py", line 16, in <module>
    win.make_window(500, 500)
  File "c:/Users/???/Desktop/Leahnn Files/Python Projects/library/lib.py", line 11, in make_window
    new_window.geometry(width + "x" + height)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

有没有办法将“int”转换为“str”数据类型?

回答

最简单的解决方案是使用格式化的字符串文字(“f-string”)

new_window.geometry(f"{width}x{height}")


以上是Tkinter:类型错误:+不支持的操作数类型:'int'和'str'的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>