Variable problem

I created a global variable to use to read and manipulate images. But there’s a problem. I cant change the variable. Println function returns nil for the variable. I’m so confused.

package main

import (
	"fmt"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/canvas"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/storage"
)

var img *canvas.Image

func main() {
	a := app.New()
	w := a.NewWindow("GoShopy")
	w.Resize(fyne.NewSize(600, 600))
	w.SetMaster()
	w.CenterOnScreen()
	save := fyne.NewMenuItem("Save", nil)
	quit := fyne.NewMenuItem("Quit", nil)
	brightness := fyne.NewMenuItem("Brightness", nil)
	contrast := fyne.NewMenuItem("Contrast", nil)
	gamma := fyne.NewMenuItem("Gamma", nil)
	saturation := fyne.NewMenuItem("Saturation", nil)
	open := fyne.NewMenuItem("Open", func() {
		file_Dialog := dialog.NewFileOpen(
			func(uc fyne.URIReadCloser, _ error) {
				img = canvas.NewImageFromFile(uc.URI().Name())
				img.FillMode = canvas.ImageFillContain
				img.SetMinSize(fyne.NewSize(600, 600))
				content := container.NewHBox(img)
				w.SetContent(content)
				w.Show()
			}, w)
		file_Dialog.SetFilter(
			storage.NewExtensionFileFilter([]string{".jpeg", ".jpg"}))
		file_Dialog.Show()
	})
	fmt.Println(img) // returns nil
	NewMenu1 := fyne.NewMenu("File",
		open, save, quit)
	NewMenu2 := fyne.NewMenu("Colors",
		brightness, contrast, gamma, saturation)
	menu := fyne.NewMainMenu(NewMenu1, NewMenu2)
	w.SetMainMenu(menu)
	w.ShowAndRun()
}

I’m not familiar with fyne, but it looks to me like the code that sets img doesn’t run until the file is opened via the menu, so fmt.Println will show nil while the menu is being constructed. Try moving the fmt.Println call into the function that loads the image.

1 Like