我想知道如何使用 tkinter 模块将按钮放入 Canvas 内。这个问题被问到了,但那是5年前的事了,而且版本不同,所以这对我的情况来说不太方便,而且我还是个初学者,所以我只理解了最佳答案中大约3/4的代码。这是问题:How to make a Button using the tkinter Canvas widget?
from tkinter import *
root = Tk()
c=Canvas(root,width=200,height=150,bg='blue')
c.pack(side = 'top')
c.create_text(100,50,anchor='c',fill='orange',font='Times 28',text='List')
button = Button(root, text="Quit",command=root.destroy)
button.pack()
mainloop()
当我运行此代码时,它会在我的 Canvas 下方而不是 Canvas 上创建按钮。我在 https://docs.python.org/3.7/library/tkinter.html 上寻求帮助我正在使用的 IDE 指南。我找不到将按钮放在 Canvas 上的方法,即使我可能错过了某些东西,也可能没有错过。如果这个问题被认为没有帮助或不必要,我深表歉意,并将立即关闭它。
Python 版本:3.7
级别:初级
运行代码: IDLE 64 位
操作系统: Windows 10
最佳答案
当您使用 pack()
时,tkinter 会将按钮放置在其主控(根)上,并且绘制 Canvas 的区域已被占用。
要将按钮放置在 Canvas 上,您应该在 Canvas 上使用函数create_window()
:
from tkinter import *
root = Tk()
c = Canvas(root,width=200,height=150,bg='blue')
c.pack(side = 'top')
c.create_text(100, 50, anchor='c', fill='orange', font='Times 28', text='List')
button = Button(root, text="Quit", command=root.destroy)
canvas_widget = c.create_window(100, 100, window=button)
root.mainloop()
关于python - 如何在 python 3.7 中的 Tk Canvas 内创建按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52846255/