我对 tkinter 很陌生,对 python 也很陌生,所以我决定使用 tkinter 作为练习来构建一个“合成器”。到目前为止它可以工作,但我不知道如何使键盘看起来像真正的钢琴键盘,即黑键丢失了。有没有办法在 tkinter 中塑造按钮的形状,这样我就可以挤压黑色 键之间或可能将黑键覆盖在白键之上?
到目前为止我的代码:
from tkinter import *
from functools import partial
import pygame
pygame.mixer.init()
#directory name where sounds are
direc='/Users/nol975/Desktop/tiny-piano00/Piano-'
listofnames=['A4','A5','D#4','D#5','C1','F#5','C3','C4','C5','C6','F#4']
listofkeys=[direc+x+'.wav' for x in listofnames]
def clicked(a):
(pygame.mixer.Sound(listofkeys[a]).play())
#**********GUI**********
root=Tk()
root.title('My cool synth')
#keyboard
synthframe=Frame(root).pack(side= BOTTOM, anchor='n')
for i in range(len(listofnames)):
Button(synthframe,text=listofnames[i], command=partial(clicked,i)).pack(side=LEFT, fill=BOTH, expand=1)
#Menu bar on top
menu = Menu(root)
root.config(menu=menu)
submenu = Menu(menu)
menu.add_cascade(label='File', menu=submenu)
submenu.add_command(label='Quit', command=root.destroy)
root.mainloop()
另外,如果我的代码到目前为止很草率,我会很感激纠正/反馈
最佳答案
我没有根据您的具体示例进行定制,但我尝试使用下图中绘制的网格将钢琴键建模为网格。每个白键由三列两行(蓝色轮廓)组成,每个黑键由两列一行(绿色轮廓)组成。当然,黑键应该放在白键的上面。
使用此模型,您可以将所有键(首先是白键,然后是黑键)放置在具有定义的尺寸的网格上,并且黑键相对于白键向右移动两行。使用 grid() 将一个按钮(部分)放在另一个按钮之上效果非常好。我定义了一个列表([1, 1, 0, 1, 1, 1, 0]
)来指示黑键是否应该放在白键之后。
import tkinter as tk
def clicked(color, num):
print(color + ': ' + str(num))
root = tk.Tk()
scales = 3
root.geometry('{}x200'.format(300 * scales))
white_keys = 7 * scales
black = [1, 1, 0, 1, 1, 1, 0] * scales
for i in range(white_keys):
tk.Button(root, bg='white', activebackground='gray87', command=lambda i=i: clicked('White', i)).grid(row=0, column=i*3, rowspan=2, columnspan=3, sticky='nsew')
for i in range(white_keys - 1):
if black[i]:
tk.Button(root, bg='black', activebackground='gray12', command=lambda i=i: clicked('Black', i)).grid(row=0, column=(i*3)+2, rowspan=1, columnspan=2, sticky='nsew')
for i in range(white_keys * 3):
root.columnconfigure(i, weight=1)
for i in range(2):
root.rowconfigure(i, weight=1)
root.mainloop()
使用scales=3
,这给出了
你可以对此进行足够的调整,但我实际上非常喜欢这个结果。
关于Python 3.x tkinter : Buttons of specific shapes or Button overlay,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51783787/