canvas.create_window无法正常工作? [英] canvas.create_window not working?
问题描述
我想在我的画布上放置一个小部件.我编写了以下函数来创建一个按钮并显示它.在画布的x坐标的中心.
I want to place a widget in my canvas. I have written the following function to create a button and display it. in the center of the x coordinate of my canvas.
def Button_Placer():
label1=Label(canvas, width =20, height = 2, font = font2, text="")
label1.pack()
def Show_Name():
name=NameGenerator()
label1.config(text=name)
button1=Button(canvas, text="Generate Name", width=20, height=4, font=font1, command=Show_Name)
button1=canvas.create_window(250, 300)
我还在顶部创建了一个画布:
I have also created a canvas at the top:
canvas = Canvas(root, width=500, height = 500, bg="red")
canvas.pack()
很不幸,canvas.create_window无法正常工作..pack()工作不过不是我所需要的.我看了其他示例,但是它们都没有面向对象编程,因此对我的理解并不重要.
Unfortunately the canvas.create_window does not work. .pack() works however is not what i need. I have looked at other examples however they are all off OOP and therefore do not find it relevant for my understanding.
推荐答案
@CommonSense写道,请尝试 canvas.create_window(200,200,window = button1)
.
As @CommonSense writes, try canvas.create_window(200, 200, window=button1)
.
也;您在函数内创建 label1
,当函数退出时,名称 label1
将被垃圾回收.
Also; you create label1
inside a function and when the functioin exits the name label1
will be garbage collected.
在画布上创建小部件时,引用是整数;该小部件在画布上的索引.如果您使用小部件名称作为画布小部件的引用,则会丢失对实际小部件的引用.
When you create widgets on canvas the reference is an integer; the index of that widget on the canvas. If you use the widget name as reference for the canvas widget you lose the reference to the actual widget.
请尝试以下示例:
from tkinter import *
root = Tk()
canvas = Canvas(root, width=500, height=500, bg="red")
canvas.pack()
def Show_Name():
name = 'A name' # No function NameGenerator()
label1.config(text=name)
button1 = Button(canvas, text="Generate Name", width=20, height=4,
command=Show_Name)
canvas_button1 = canvas.create_window(250, 300, window=button1)
label1 = Label(canvas, width=20, height=2, text="")
canvas_label1 = canvas.create_window(250, 200, window=label1)
这篇关于canvas.create_window无法正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!