這是我的代碼:
from time import sleep
from tkinter import *
def moveWin(win, velx, vely):
x = win.winfo_x()
y = win.winfo_y()
win.geometry(f" {str(x velx)} {str(y vely)}")
downx, downy = x width, y height
global sWidth
global sHeight
if x <= 0 or downx >= sWidth:
velx = -velx
if y <= 0 or downy >= sHeight:
vely = -vely
return [x, y, downx, downy]
root = Tk()
width = 300
height = 300
velx = 1
vely = 1
sWidth = root.winfo_screenwidth() # gives 1366
sHeight = root.winfo_screenheight() # gives 1080
root.geometry(" 250 250")
while True:
root.update()
root.geometry("300x300")
pos = moveWin(root, velx, vely)
print(pos)
sleep(0.01)
我想在它接觸螢屏邊緣時彈回我的視窗,但它剛剛離開螢屏我的代碼有什么問題?請幫忙
uj5u.com熱心網友回復:
如果您需要修改全域變數,則不要將它們作為引數傳遞。相反,添加
def movewin(win):
global velx
global vely
在您的功能頂部。
大跟進
您的應用程式中更重要的問題與坐標有關。 root.winfo_x()并且root.winfo_y()不要回傳視窗的左上角。相反,它們回傳可繪制區域的左上角、邊框內和標題欄下方。這搞砸了你的繪圖,意味著你試圖定位螢屏底部,Tkinter 修復了它。
這里的解決方案是自己跟蹤 x 和 y 位置,而不是從 Tk 中獲取它們。
Tkinter 大多是垃圾。你會通過看可以更好地服務pygame于簡單的游戲,或在一個真正的GUI系統,如Qt或wxPython應用程式。
from time import sleep
from tkinter import *
class Window(Tk):
def __init__(self):
Tk.__init__(self)
self.width = 300
self.height = 300
self.velx = 1
self.vely = 1
self.pos = (250,250)
self.geometry(f"{self.width}x{self.height} {self.pos[0]} {self.pos[1]}")
def moveWin(self):
x = self.pos[0] self.velx
y = self.pos[1] self.vely
downx, downy = x self.width, y self.height
sWidth = self.winfo_screenwidth() # gives 1366
sHeight = self.winfo_screenheight() # gives 1080
if x <= 0 or downx >= sWidth:
self.velx = -self.velx
if y <= 0 or downy >= sHeight:
self.vely = -self.vely
self.pos = (x,y)
self.geometry(f" {x} {y}")
return [x, y, downx, downy]
root = Window()
while True:
root.update()
pos = root.moveWin()
print(pos)
sleep(0.01)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/387100.html
