Python tkinter |如何让按钮居中?

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

作为一个 Python 新手,我目前正在编写 CPS 计数器,但我似乎无法将 Click 按钮居中。

这是我到目前为止得到的:

from tkinter import *
from threading import Timer
import time

# CPS Counter Code

print ("This is a test showing how much Clicks Per Second you have.")
time.sleep(2)
choice = input("How many seconds do you want CPS timer to be?: ")
choice = int(choice) # duration of timer
turn = 0
cps = 0 # cps starts at zero
num = 0

window = Tk()
window.title('CPS Counter') 
window.geometry("800x600") 
window.configure(bg = 'gray7')

def clicks(): # overall cps
    global num
    cps = num/choice
    cps = str(cps) # converts cps to string
    print("Your record is " + cps + " CPS!")
trackcps = Timer(choice, clicks ) 

def addcps(): 
    global num
    num += 1

def runcps():
    global turn
    if turn == 1: 
        addcps()
    
    if turn == 0:
        trackcps.start() 
        turn += 1

button = Button(window,  # button customization
                text = 'Click!', 
                padx=200,
                pady=100, 
                font=("Ariel Bold", 32), 
                command=runcps,
                bg = "black",
                fg = "white") 
button.place(relx=0.5, rely=0.5, anchor=CENTER) # supposed to center the button (problem)
button.pack()


window.mainloop() # prevents window from closing

我尝试做button.place(relx = 0.5,rely = 0.5,anchor = CENTER),但它似乎仍然没有使按钮居中。

我该如何解决这个问题?

python tkinter button
1个回答
0
投票

删除“button.pack()”,因为您已经放置了它,无需再次打包。

#### Code used above ####
button = Button(window,  # button customization
                text = 'Click!', 
                padx=200,
                pady=100, 
                font=("Ariel Bold", 32), 
                command=runcps,
                bg = "black",
                fg = "white") 
button.place(relx=0.5, rely=0.5, anchor=CENTER) # supposed to center the button (problem)
#button.pack()


window.mainloop() # prevents window from closing
© www.soinside.com 2019 - 2024. All rights reserved.