首页 > 解决方案 > 如何在 Python Tkinter 中将画布的宽度设置为屏幕的宽度?

问题描述

我有一个画布tkinter需要跨越屏幕的整个宽度,但无法让它工作。

我试图使屏幕宽度成为一个变量并将其作为参数传递给类但向我抛出一个错误,我试图将其设置root.winfo_screenwidthself.winfo_screenwidth但它只是向我抛出一个错误,我在 www 上寻找答案但我看到的最接近的是如何设置root屏幕尺寸。

这是我的代码:

import tkinter as tk


class Window(tk.Frame):
    def __init__(self, master, **kwargs):
        super().__init__(master, **kwargs)

        canvas = tk.Canvas(self, width="", height=100) #How to set the width to the screen width?
        canvas.config(bg="#505050")
        canvas.pack()


def mainloop_scw():
    root = tk.Tk()
    root.title("Editor - Adventure")
    screenwidth = root.winfo_screenwidth()
    screenheight = root.winfo_screenheight()
    root.geometry("%sx%s" %(screenwidth, screenheight))
    root.config(bg="#303030")
    app = Window(root)
    app.config(bg="#303030")
    app.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
    root.mainloop()


if __name__ == "__main__":
    mainloop_scw()

有谁知道我如何将canvas宽度设置为screenwidth

标签: pythoncanvastkinterscreen

解决方案


您不需要明确设置画布的宽度。pack具有可用于强制画布占据整个屏幕宽度的选项。

canvas.pack(fill="x")

推荐阅读