Advertisement
here2share

# Tk_scroll_widgets_only.py

Jun 15th, 2019
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.25 KB | None | 0 0
  1. # Tk_scroll_widgets_only.py
  2.  
  3. import Tkinter as tk
  4.  
  5. root = tk.Tk()
  6. root.grid_rowconfigure(0, weight=1)
  7. root.columnconfigure(0, weight=1)
  8.  
  9. frame_main = tk.Frame(root, bg="gray")
  10. frame_main.grid(sticky='news')
  11.  
  12. label1 = tk.Label(frame_main, text="Label 1", fg="green")
  13. label1.grid(row=0, column=0, pady=(5, 0), sticky='nw')
  14.  
  15. label2 = tk.Label(frame_main, text="Label 2", fg="blue")
  16. label2.grid(row=1, column=0, pady=(5, 0), sticky='nw')
  17.  
  18. label3 = tk.Label(frame_main, text="Label 3", fg="red")
  19. label3.grid(row=3, column=0, pady=5, sticky='nw')
  20.  
  21. # Create a frame for the canvas with non-zero row&column weights
  22. frame_canvas = tk.Frame(frame_main)
  23. frame_canvas.grid(row=2, column=0, pady=(5, 0), sticky='nw')
  24. frame_canvas.grid_rowconfigure(0, weight=1)
  25. frame_canvas.grid_columnconfigure(0, weight=1)
  26. # Set grid_propagate to False to allow 5-by-5 buttons resizing later
  27. frame_canvas.grid_propagate(False)
  28.  
  29. # Add a canvas in that frame
  30. canvas = tk.Canvas(frame_canvas, bg="yellow")
  31. canvas.grid(row=0, column=0, sticky="news")
  32.  
  33. # Link a scrollbar to the canvas
  34. vsb = tk.Scrollbar(frame_canvas, orient="vertical", command=canvas.yview)
  35. vsb.grid(row=0, column=1, sticky='ns')
  36. canvas.configure(yscrollcommand=vsb.set)
  37.  
  38. # Create a frame to contain the buttons
  39. frame_buttons = tk.Frame(canvas, bg="blue")
  40. canvas.create_window((0, 0), window=frame_buttons, anchor='nw')
  41.  
  42. # Add 9-by-5 buttons to the frame
  43. rows = 9
  44. columns = 5
  45. buttons = [[tk.Button() for j in xrange(columns)] for i in xrange(rows)]
  46. for i in range(0, rows):
  47.     for j in range(0, columns):
  48.         buttons[i][j] = tk.Button(frame_buttons, text=("%d,%d" % (i+1, j+1)))
  49.         buttons[i][j].grid(row=i, column=j, sticky='news')
  50.  
  51. # Update buttons frames idle tasks to let tkinter calculate buttons sizes
  52. frame_buttons.update_idletasks()
  53.  
  54. # Resize the canvas frame to show exactly 5-by-5 buttons and the scrollbar
  55. first5columns_width = sum([buttons[0][j].winfo_width() for j in range(0, 5)])
  56. first5rows_height = sum([buttons[i][0].winfo_height() for i in range(0, 5)])
  57. frame_canvas.config(width=first5columns_width + vsb.winfo_width(),
  58.                     height=first5rows_height)
  59.  
  60. # Set the canvas scrolling region
  61. canvas.config(scrollregion=canvas.bbox("all"))
  62.  
  63. # Launch the GUI
  64. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement