使用while循环时tkinter canvas不会打开

问题描述 投票:1回答:1

我正在尝试使用tkinter并使用以下代码作为测试人员:

import keyboard
from time import sleep
from tkinter import *

tk = Tk()
canvas = Canvas(tk, width=400, height=400)
canvas.pack()

a = 0
if keyboard.is_pressed('q'):
    a = 1
if a == 1:
    canvas.create_line(0,0,400,400)
    tk.mainloop()

运行此代码时没有画布。我已经尝试使用调试消息而不是创建一行,以及转移“tk.mainloop”但画布没有显示。但是,当我不使用while循环而是使用for循环时,画布会出现。我计划制作的程序需要无限循环。有没有办法以与tkinter一起使用的方式执行此操作?

提前谢谢,我对一个可能归结为我的一些简单错误的问题道歉。

python tkinter tkinter-canvas
1个回答
1
投票

Tkinterbind()为键/鼠标/事件分配功能,所以你不需要keyboard模块和while循环。

import tkinter as tk

def myfunction(event):
    canvas.create_line(0, 0, 400, 400)

root = tk.Tk()

canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()

root.bind('q', myfunction)

root.mainloop()

编辑:更有趣的东西 - 每个q创建随机线

import tkinter as tk
import random

def myfunction(event):
    x = random.randint(0, 400)
    y = random.randint(0, 400)
    canvas.create_line(x, y, 400, 400)

root = tk.Tk()
canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()

root.bind('q', myfunction)

root.mainloop()

enter image description here

或者像毕加索一样

import tkinter as tk
import random

def myfunction(event):
    x1 = random.randint(0, 400)
    y1 = random.randint(0, 400)
    x2 = random.randint(0, 400)
    y2 = random.randint(0, 400)
    canvas.create_line(x1, y1, x2, y2)

root = tk.Tk()
root.title('Picasso')

canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()

root.bind('q', myfunction)

root.mainloop()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.