I'm trying to add another button to my GUI by pressing a button on the GUI itself. Essentially I'm just trying to update it but I'm relatively new to OOP so I'm having issues with scope.
This is what I have so far...
1 #!/usr/bin/env python
2 import random, gi, sys
3 from gi.repository import Gtk
4 import itertools
23 class Deck:
24 """A sample card deck"""
25 def __init__(self):
26 deck = []
27 self.color_list = ["red", "green", "blue"]
28 for color in self.color_list:
29 for i in range (1,2):
30 deck.append((color, i))
31 self.deck = deck
32
33 def draw_card(self):
34 print self.deck
35 try:
36 card = self.deck.pop()
37 print self.deck
38 return card
39 except IndexError:
40 print "No cards in deck!"
41 return
56 class MyWindow(Gtk.Window):
57
58 def __init__(self):
59 Gtk.Window.__init__(self, title="RGB 3, 2, 1... GO!")
60 self.set_border_width(10)
61 self.set_size_request(450,150)
62
63 grid = Gtk.Grid()
64 self.add(grid)
65
66 draw_button = Gtk.Button(label="Draw Card")
67 draw_button.connect("clicked", self.on_draw_button_clicked)
68 grid.attach(draw_button,0,0,1,1)
69
70 end_button = Gtk.Button(label="End Game")
71 end_button.connect("clicked", self.on_stop_button_clicked)
72 grid.attach_next_to(end_button,draw_button,Gtk.PositionType.RIGHT,1,1)
73
74 update_button = Gtk.Button(label="Update")
75 update_button.connect("clicked", self.update, grid)
76 grid.attach_next_to(update_button,end_button,Gtk.PositionType.RIGHT,1,1)
77
78 def update(self, widget, grid):
79 card1_button = Gtk.Button(label="card1")
80 card1_button.connect("clicked", self.on_card1_button_clicked)
81 grid.attach_next_to(card1_button,draw_button,Gtk.PositionType.BOTTOM,3,1)
82
83 def on_draw_button_clicked(self, widget):
84 +--- 13 lines: card = my_deck.draw_card()----------------------------------------------------------------------------------------------------
97
98 def on_stop_button_clicked(self, widget):
99 Gtk.main_quit()
100
101 def on_card1_button_clicked(self, widget):
102 Gtk.main_quit()
121 # Objects must be instantiated here
122 my_deck = Deck()
123 print my_deck.deck
124 win = MyWindow()
125 win.connect("delete-event", Gtk.main_quit)
126 win.show_all()
127 Gtk.main()
When I run this, my GUI pops open. And when I hit my update button I get the following error:
Traceback (most recent call last):
File "game1.py", line 85, in update
grid.attach_next_to(card1_button,draw_button,Gtk.PositionType.BOTTOM,3,1)
NameError: global name 'draw_button' is not defined
How do I get my update function to recognize the GUI/grid I've already created in the def init function? Is there a better way to do what I want?