试图在tkinter中更改字体。 按钮一直工作到我到达第七位 我的猜测是Serif女士是两个字, 通常我会在两个字前加上“” 但是我写程序的方式不对。
我的问题是如何修复我的函数以接受字体 两个单词的名字。
以下是输出:
Counter: 1 Fontz: Terminal 12 bold
Counter: 2 Fontz: Fixedsys 12 bold
Counter: 3 Fontz: Modern 12 bold
Counter: 4 Fontz: Roman 12 bold
Counter: 5 Fontz: Script 12 bold
Counter: 6 Fontz: Courier 12 bold
Counter: 7 Fontz: MS Serif 12 bold
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Slim 960\AppData\Local\Programs\Py
return self.func(*args)
File "Tkinter001.py", line 83, in button_font
logo = tk.Label(root, compound = tk.CENTER, tex
.grid(row=0, column=0)
File "C:\Users\Slim 960\AppData\Local\Programs\Py
Widget.__init__(self, master, 'label', cnf, kw)
File "C:\Users\Slim 960\AppData\Local\Programs\Py
(widgetName, self._w) + extra + self._options(c
_tkinter.TclError: expected integer but got "Serif"
代码:
from tkinter import font
import os
import random
import tkinter as tk
# Give 10 blank lines
print("\n"*10)
# Create path to GURPS gif files
home = os.path.expanduser('~')
dt = desktop = os.path.join(home,'Desktop')
p3p = python_3_projects = os.path.join(dt, "Python 3 Projects")
ilfru = images_labeled_for_reuse = os.path.join(p3p,"Images Labeled for Reuse")
gurps = os.path.join(ilfru,'GURPS')
gg = os.path.join(gurps, 'GIF')
# Count all then number of GIFS in Folder GIFS
fc = 0
for root, dir, files in os.walk(gg):
for filename in files:
fc += 1
print("Filenames: ",filename)
print("The total number of files is: ",fc)
# Generate Random Number from maximum number of files
rn = random.randint(1,fc)
print("The random number is: ", rn)
# Assign a file path to lip (logo_image_path)
fc = 0
for root, dir, files in os.walk(gg):
for filename in files:
fc += 1
if fc == rn:
lip = os.path.join(gg,filename)
print("The Random Number is: ",rn)
print("The choosen file is: ", filename)
print("The file counter is: ", fc)
print("The file path is: ", lip)
f_counter = 0
ff = []
# Cycle through Fonts
def button_font():
global f_counter
global ff
global fontz
f_counter +=1
fontz = str(ff[f_counter]) + " 12 bold"
print("Counter: ",f_counter," Fontz: ",fontz)
logo = tk.Label(root, compound = tk.CENTER, text = "GURPS\n CHARACTER\n SHEET", font=fontz, fg ="white", image=ggpi).grid(row=0, column=0)
root = tk.Tk()
ggpi =gurps_gif_photo_image = tk.PhotoImage(file=lip)
# List of all tkinter fonts
tk_fonts = font.families()
for font in tk_fonts:
ff.append(font)
print(ff)
button_font()
logo = tk.Label(root, compound = tk.CENTER, text = "GURPS\n CHARACTER\n SHEET", font=fontz, fg ="white", image=ggpi).grid(row=0, column=0)
Label1 = tk.Label(root, text="Name: ", font ="bold").grid(row=0, column = 1)
button = tk.Button(root, text="Font Changer", command=button_font).grid(row=3,column=3)
root.mainloop()
答案 0 :(得分:3)
使用元组而不是字符串-当名称具有多个空格时,tkinter不会将名称与大小混淆:
这有效:
fontz = (str(ff[f_counter]), 12, "bold")
logo = tk.Label(root, compound=tk.CENTER,
text="GURPS\n CHARACTER\n SHEET",
font=fontz,
fg ="white",
image=ggpi
).grid(row=0, column=0)