如何向每个窗口添加滚动条

qzwqbdag  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(301)

我有以下代码,我在stackoverflow上基于 Backbone.js 进行开发。我理解,但我在添加滚动条时遇到了问题。在第1页,我输入数字并按“ok”后,生成一定数量的条目。如果数字太大,我无法填写全部,因此需要一个滚动条。我尝试了不同的解决方案,但没有一个奏效。我以前从未使用过滚动条,有人能帮我吗?提前谢谢

import tkinter as tk                # python 3
from tkinter import Scrollbar, font as tkfont
from typing_extensions import IntVar  # python 3
from Classi_Utenti import * 

class SampleApp(tk.Tk, FinanziatoreSemplice):

    def __init__(self, *args,**kwargs):
        tk.Tk.__init__(self, *args,**kwargs)

        self.labels_finanziatori = {
        'principale': [],
        'capitale_investito': [], 
        'tasso': [], 
        'tempo': []
        }

        self.dict_finanziatori = {
        'numero': [],
        'capitale_investito': [], 
        'tasso': [], 
        'tempo': [],
        }

        self.Finanziatori_Semplici = []

        self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic")

        # the container is where we'll stack a bunch of frames
        # on top of each other, then the one we want visible
        # will be raised above the others
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}

        for F in (StartPage, FinanziatoriSemplici):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame

            # put all of the pages in the same location;
            # the one on the top of the stacking order
            # will be the one that is visible.
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame("StartPage")

    def show_frame(self, page_name):
        '''Show a frame for the given page name'''
        frame = self.frames[page_name]
        frame.tkraise()
        # notify frame that it is raised via virtual event
        #frame.event_generate("<<Raised>>")

    def back_frame(self, page_name, old_frame):
        '''Show a frame for the given page name'''
        old_frame = self.frames[old_frame]
        frame = self.frames[page_name]
        frame.tkraise()
        for widgets in old_frame.winfo_children():
            widgets.destroy()
        # notify frame that it is raised via virtual event
        #frame.event_generate("<<back>>")

class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="Benvenuti nel framework di configurazione", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)

        button1 = tk.Button(self, text='Inizia la configurazione', command=lambda: controller.show_frame("FinanziatoriSemplici"))
        button1.pack()

class FinanziatoriSemplici(tk.Frame, FinanziatoreSemplice):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        self.numero_utenti=tk.IntVar()
        self.Finanziatori_Semplici = [] 

        self.labels_finanziatori = {
            'principale': [],
            'capitale_investito': [], 
            'tasso': [], 
            'tempo': []
            }

        self.dict_finanziatori = {
            'numero': [],
            'capitale_investito': [], 
            'tasso': [], 
            'tempo': [],
            }
        tk.Label(self, text="Configurare I Finanziatori", font=controller.title_font).grid(row=0, column = 0)
        tk.Label(self, text="Inserire il numero di utenti da configurare").grid(row=1, column = 0)
        self.entry_utenti = tk.Entry(self, text="Inserire numero Utenti", textvariable = self.numero_utenti)
        self.entry_utenti.grid(row=1, column=1)
        self.btn_utenti = tk.Button(self, text="OK", command= lambda: InizializzaUtenti(self.entry_utenti.get()))
        self.btn_utenti.grid(row=1, column=2)

        def InizializzaUtenti(num):    
            self.numero_utenti = int(num)
            k=3

            for i in range(0, self.numero_utenti):
                #MAIN label del finanziatore
                self.labels_finanziatori['principale'].append(tk.Label(self, text="Dati finanziatore numero "+str(i+1) +":\n"))
                self.labels_finanziatori['principale'][i].grid(row=i*k+3, column = 0)
                k = k+1
                #Label capitale investito
                self.labels_finanziatori['capitale_investito'].append(tk.Label(self, text="Dati sul capitale investito del finanziatore "+str(i+1)))
                self.labels_finanziatori['capitale_investito'][i].grid(row=i*k+4, column = 0, sticky= "W")
                #Entry widget capitale investito
                self.dict_finanziatori['capitale_investito'].append(tk.Entry(self, text = "Inserire il Capitale investito dal finanziatore "+str(i+1)))
                self.dict_finanziatori['capitale_investito'][i].grid(row=i*k+4, column = 1)
                k= k+1
                #Label Tasso di interesse
                self.labels_finanziatori['tasso'].append(tk.Label(self, text="Dati sul tasso di interesse del finanziatore "+str(i+1)))
                self.labels_finanziatori['tasso'][i].grid(row=i*k+5, column = 0,sticky= "W")
                #Entry widget tasso
                self.dict_finanziatori['tasso'].append(tk.Entry(self, text = "Inserire il tasso di interesse"))
                self.dict_finanziatori['tasso'][i].grid(row=i*k+5, column = 1)
                k= k+1
                ############################## N.B. L'ultima label ha pady
                #Label Tempo di ritorno 
                self.labels_finanziatori['tempo'].append(tk.Label(self, text="Inserire il tempo di ritorno per l'investimento per il finanziatore "+str(i+1), anchor='w'))
                self.labels_finanziatori['tempo'][i].grid(row=i*k+6, column = 0, pady=(0, 10), sticky= "W")
                #Entry widget tempo
                self.dict_finanziatori['tempo'].append(tk.Entry(self, text = "Inserire il tempo di ritorno per l'investimento"))
                self.dict_finanziatori['tempo'][i].grid(row=i*k+6, column = 1, pady=(0, 10))
                k= k+1

                tk.Button(self, text="Valida", command = lambda: ValidaFinanziatore(self.dict_finanziatori['capitale_investito'][i])).grid(row=i*k+6, column = 2, pady=(0, 10))
                #Crea bottone per ogni finanziatore per inizializzarlo dove viene verificato anche l'input
                #self.Finanziatori_Semplici.append(FinanziatoreSemplice(float(x), float(self.dict_finanziatori['tasso'][i].get()), float(self.dict_finanziatori['tempo'][i].get()), int(i)))

            def ValidaFinanziatore(capitale):
                return

if __name__ == "__main__":
    app = SampleApp()
    app.geometry("900x900")
    app.mainloop()
yshpjwxd

yshpjwxd1#

下面的代码可能会有所帮助。 makescrollbar 为您提供无限的tkinter滚动条,包括垂直和水平的角按钮,四元是布局的数据,由索引值象限=(0,1,2,3)控制
尝试更改象限并运行程序以查看不同的布局
这些函数将允许您在任何tk |顶级对象上实现滚动条。

import tkinter

quad = [ [ 0, 0, 0, 1, 1, 0, 1, 1 ],
         [ 0, 1, 0, 0, 1, 1, 1, 0 ],
         [ 1, 1, 1, 0, 0, 1, 0, 0 ],
         [ 1, 0, 1, 1, 0, 0, 0, 1 ] ]

def getquadrant( p ) ->'quad list[ p ]':
    '''getquadrant( p(int) )'''
    return quad[ p%4 ]

def flexx( m, r = 0, c = 0, rweight = 1, cweight = 1 ):
    if r !=  None:
        m.rowconfigure( r, weight = rweight )
    if c !=  None:
        m.columnconfigure( c, weight = cweight )

def grid( r = 0, c = 0, s = 'nsew', rs = 1, cs = 1 ):
    return dict( row=r, column=c, rowspan=rs, columnspan=cs, sticky=s )

# m = main object to connect scrollbars to ( Text, Canvas, Listbox )

# p = parent|master

# q = quadrant int 0,1,2,3

# f = function to connect to corner button

# w = scrollbar width 0, 1, 2 ( smallest to biggest )

def makescrollbar( p, m, q, f = None, w = 0 ):
    v = tkinter.Scrollbar(
        p, command = m.yview, width = [12, 14, 16][w%3], orient = "vertical" )
    h = tkinter.Scrollbar(
        p, command = m.xview, width = [12, 14, 16][w%3], orient = "horizontal" )
    m.config( yscrollcommand = v.set, xscrollcommand = h.set )
    k = tkinter.Button(
        p, takefocus = 0, command = f, font = 'Consolas 5 normal' )
    q = getquadrant( q )
    # grid everything
    [ x.grid(grid(r=r,c=c)) for x,r,c in [ (v,q[2],q[3]),(h,q[4],q[5]),(k,q[6],q[7]) ] ]
    # flexx parent
    flexx( p, r = q[0], c = q[1] )
    # grid main
    m.grid( grid( r = q[0], c = q[1] ) )
    return v, h, k

quadrant = 1 # change is to experiment with layout

master = tkinter.Tk()
master.title( 'Text Layout' )

if True:
    main = tkinter.Text(
        master, width = 80, height = 24, insertofftime = 0, block = 1,
        font = "Consolas 10 normal", selectbackground = "#888888",
        selectforeground = "#ffffff", insertborderwidth = 1, insertwidth = 3,
        insertbackground = "#ff0000", undo = 1, maxundo = 0, wrap = "none") 

else:

    main = tkinter.Canvas(
        master, width = 600, height = 400, scrollregion = "0 0 2000 2000",
        background = "#000000", cursor = "crosshair",
        xscrollincrement = 1, yscrollincrement = 1 )

# do it

v, h, c = makescrollbar( master, main, quadrant, f = None, w = 2 )

main.focus()

tkinter.mainloop()

相关问题