猿问

如何通过新窗口更改 tkinter 画布的大小?

所以我有一个带有画布的 Tkinter 屏幕。我想通过创建一个具有条目小部件的新窗口来更改画布的大小。所以我创建了一个新屏幕并添加了 2 个条目小部件。我想从这些小部件中获取值,并基于此......它应该改变画布的大小。我尝试这样做一个小时,但没有成功。请帮助我。


这是我的代码


from tkinter import *

# create root window 

root = Tk()


# Create Canvas

canvas = Canvas(root, width=50, height=50)


# Create an additional window (the one that is used to enter the new geometry)

dialog = Toplevel(root)


# Add entry widgets for width and height to the new window

width_entry = tk.Entry(dialog)

height_entry = tk.Entry(dialog)


# Add a button to the new window that applies the given width and height 

apply_button = Button(dialog, text = 'Apply geometry', command = lambda: canvas.geometry(width_entry.get()+'x'+height_entry.get()))


# Its not possible to get the geometry of a canvas in tkinter...so how do I change the size.


# display the entry boxes and button

width_entry.pack()

height_entry.pack()

apply_button.pack()


# start the tk mainloop

root.mainloop()

请帮助我


元芳怎么了
浏览 115回答 1
1回答

慕村225694

您正在寻找的命令是canvas.config在这里,我调整了给定的代码:import tkinter as tk# create root window root = tk.Tk()# Create Canvascanvas = tk.Canvas(root, width=50, height=50)canvas.pack()# Create an additional window (the one that is used to enter the new geometry)dialog = tk.Toplevel(root)# Add entry widgets for width and height to the new windowwidth_entry = tk.Entry(dialog)height_entry = tk.Entry(dialog)# Add a button to the new window that applies the given width and height apply_button = tk.Button(dialog, text = 'Apply geometry', command = lambda: canvas.config(width=width_entry.get(), height=height_entry.get()))# display the entry boxes and buttonwidth_entry.pack()height_entry.pack()apply_button.pack()# start the tk mainlooproot.mainloop()我还改变了其他一些事情:您从 tkinter 导入了 *,但对于某些项目,您仍然以tk.;开头。我将它们全部更改为匹配,并将导入也更改为匹配。(您仍然可以使用 *,但只是没有前导tk.s。)画布从来没有被打包过,所以你永远看不到那里发生了什么。还有一个建议,制作按钮的那一行真的很长。也许创建一个函数来完成 lambda 所做的事情,并将其命令分配给该函数而不是 lambda。您可能会发现,如果有人(可能是您自己的未来版本)尝试阅读您的代码,并编辑它或理解它,那么这么长的行甚至很难阅读。一般来说,尽量将所有行的字符数控制在 80 个以内。如果您还有其他问题等,请告诉我们。
随时随地看视频慕课网APP

相关分类

Python
我要回答