tk_test1.py
# -*- coding: utf-8 -*-
import os
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.title("生成 buttonBar 示例 ")
var = tk.StringVar() # 动态字符串
label = tk.Label(root, textvariable=var)
listbox = tk.Listbox(root, selectmode=tk.SINGLE)
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
def create_buttonbar(self):
self.button1 = tk.Button(self, text="选文件夹", command=self.opendir)
self.button1.pack(side="left", padx=5, pady=2)
self.button2 = tk.Button(self, text="Play", command=self.play)
self.button2.pack(side="left", padx=5, pady=2)
self.button3 = tk.Button(self, text="Stop", command=self.stop)
self.button3.pack(side="left", padx=5, pady=2)
self.button4 = tk.Button(self, text="Pause", command=self.pause)
self.button4.pack(side="left", padx=5, pady=2)
self.button5 = tk.Button(self, text="unpause", command=self.unpause)
self.button5.pack(side="left", padx=5, pady=2)
self.button6 = tk.Button(self, text="Quit", fg="red",
command=self.master.destroy)
self.button6.pack(side="left", padx=5, pady=2)
def opendir(self):
dir1 = filedialog.askdirectory()
if dir1 == '':
return 1
var.set(dir1)
os.chdir(dir1)
files = os.listdir(dir1)
if len(files) > 0:
listbox.delete(0, tk.END)
i = 0
for fname in files:
listbox.insert(i,fname)
i += 1
def play(self):
var.set(listbox.get(tk.ACTIVE))
def stop(self):
print("stop button.")
def pause(self):
print("pause button.")
def unpause(self):
print("unpause button.")
label.pack(side="top")
app = Application(master=root)
app.create_buttonbar()
app.pack()
listbox.pack(side="bottom", fill='both')
app.mainloop()
运行 python tk_test1.py