如何将滚动条添加到使用tkinter创建的窗口

时间:2017-12-09 10:00:23

标签: python tkinter scrollbar

一个简单的问答游戏

我得到了这个代码,我需要滚动条,我试图搜索如何在stackoverflow上添加它(ScrolledWindow with tix ...)但我仍然无法获得正常工作的东西。有人能帮助我吗?

from tkinter import *
from random import randint

root = Tk()
root.title("Quiz")
root.geometry("400x300")


class Window:

    def __init__(self, question, answer):
        self.text = [question, answer]
        self.createLabel()
        # self.createText()
        self.createEntry()
        self.createButton()

    def retrieve_input(self):
        # inputValue = self.textBox.get("1.0", "end-1c")
        # print(inputValue)
        if self.mystring.get() == self.text[1]:
            print("Esatto. è " + self.text[1])
            self.left['text'] = "Esatto"

    def createLabel(self):
        self.labelframe = LabelFrame(root, text="Domanda:")
        self.labelframe.pack(fill="both", expand="yes")
        self.left = Label(self.labelframe, text=self.text[0])
        self.left.pack()

    def createText(self):
        self.textBox = Text(height=1)
        self.textBox.pack()

    def createEntry(self):
        self.mystring = StringVar()
        self.myentry = Entry(root, textvariable=self.mystring).pack()

    def createButton(self):
        self.but = Button(text="Click", command=self.retrieve_input)
        self.but.pack()


for i in range(10):
    one = randint(1, 10)
    two = randint(1, 10)
    Window("Quanto fa " + str(one) + "+" + str(two) + "?", str(one + two))

root.mainloop()
  

输出

enter image description here

1 个答案:

答案 0 :(得分:2)

使用<section class="hero"> <div class="svg-container"> <a class="magic-link" href="#"> <svg class="gradient" height="60" width="320" xmlns="http://www.w3.org/2000/svg"> <defs> <linearGradient id="gradient"> <stop offset="0%" stop-color="#EB3349" /> <stop offset="95%" stop-color="#EB3349" /> </linearGradient> </defs> <rect class="rect-shape" height="60" width="320" /> <div class="text">Hover me</div> </svg> </a> </div> </section>,它看起来像这样

enter image description here

  • 我将ScrolledFrame重命名为Window,因为它更有意义
  • 我使用Questionself.question代替self.answer,以使其更具可读性。
  • 我在self.text = [question, answer]之前放置了类和函数,以使其更具可读性。
  • 我使用root = tk.Tk()代替import tkinter as tk来使其更具可读性。

from tkinter import *Question获取内部框架,并用作ScrolledFrame的父级框架。其他小部件使用LabelFrame作为父级。

顺便说一句:您labelframeentry = Entry(..).pack()分配给None,因为entry / pack() / grid()返回place()。我将None放在下一行,现在我可以直接从pack()获取文字(不含Entry

代码

StringVar