在Tkinter

时间:2015-04-30 17:53:11

标签: python tkinter

我正在尝试使用Tkinter制作一个简单的应用程序启动器(对于我使用pygame制作的游戏)。相同的代码如下。它以全屏模式运行(没有任何最大化或最小化按钮)。

import Tkinter as tk
from Tkinter import *
import random
import os
import subprocess


def call(event,x):

   print "begin"
   if x==0:
       p = subprocess.Popen("python C:\Users\Akshay\Desktop\i.py")


   p.wait()
   print "end"



root = tk.Tk()
root.geometry("1368x768+30+30")
root.overrideredirect(True)
root.geometry("{0}x{1}+0+0".format(root.winfo_screenwidth(),    root.winfo_screenheight()))

games = ['Game1','Game2','Game3','Game4','Game5','Game6','Game7','Game8']
labels = range(8)
for i in range(8):
    ct = [random.randrange(256) for x in range(3)]
    brightness = int(round(0.299*ct[0] + 0.587*ct[1] + 0.114*ct[2]))
    ct_hex = "%02x%02x%02x" % tuple(ct)
    bg_colour = '#' + "".join(ct_hex)
    l = tk.Label(root, 
            text=games[i], 
            fg='White' if brightness < 120 else 'Black', 
            bg=bg_colour)
    l.place(x = 320, y = 30 + i*150, width=700, height=100)
    l.bind('<Button-1>', lambda event, arg=i: call(event, arg))

root.mainloop()

这段代码没有问题,但我想在右侧滚动条或使用箭头键向下滚动/向下移动,这样如果我添加更多数量的标签,它们也会变得可见。

我试图从互联网上了解一些代码片段并阅读Tkinter文档,但没有理解任何内容。还试图再进行一次stackoverflow讨论,并了解框架和画布方法。

Python Tkinter scrollbar for frame

框架,画布和一切都变得有点复杂。我只是想保持简单。可以在上面的代码片段中添加一些内容,使滚动工作正常并且所有标签都可见?

enter image description here

像上面的东西,但滚动条!!

1 个答案:

答案 0 :(得分:1)

以下是MCVE如何向tkinter应用添加滚动条,隐藏滚动条以及使用向上/向下箭头或鼠标滚轮滚动。

from tkinter import *

parent=Tk() # parent object
canvas = Canvas(parent, height=200) # a canvas in the parent object
frame = Frame(canvas) # a frame in the canvas
# a scrollbar in the parent
scrollbar = Scrollbar(parent, orient="vertical", command=canvas.yview)
# connect the canvas to the scrollbar
canvas.configure(yscrollcommand=scrollbar.set)
scrollbar.pack(side="right", fill="y") # comment out this line to hide the scrollbar
canvas.pack(side="left", fill="both", expand=True) # pack the canvas
# make the frame a window in the canvas
canvas.create_window((4,4), window=frame, anchor="nw", tags="frame")
# bind the frame to the scrollbar
frame.bind("<Configure>", lambda x: canvas.configure(scrollregion=canvas.bbox("all")))
parent.bind("<Down>", lambda x: canvas.yview_scroll(3, 'units')) # bind "Down" to scroll down
parent.bind("<Up>", lambda x: canvas.yview_scroll(-3, 'units')) # bind "Up" to scroll up
# bind the mousewheel to scroll up/down
parent.bind("<MouseWheel>", lambda x: canvas.yview_scroll(int(-1*(x.delta/40)), "units"))
labels = [Label(frame, text=str(i)) for i in range(20)] # make some Labels
for l in labels: l.pack() # pack them

parent.mainloop() # run program